如何获取子进程的返回值?

发布于 2024-08-18 23:31:08 字数 1304 浏览 3 评论 0原文

程序计算从 1 到 N 的数字之和。 子进程计算偶数之和。 父进程计算奇数之和。 我想在父进程中获取子进程的返回值。我该怎么做

#include<stdio.h>
#include<errno.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>

int main()
{
    int N;
    int id;
    int fd_result;;

    printf("Enter N till which you want the sum: \n");
    scanf("%d",&N);
    if ((fd_result=creat("result", 600))== -1)
    {
        perror("Error creating file");
        exit(1);
    }
    if ((fd_result=open("result",O_TRUNC | O_RDWR)) == -1)
    {
        perror("Error Opening file");
        exit(1);
    }
    if ((id=fork())<0)
    {
        perror("Error occurred forking....!");
        exit(errno);
    }
    if (id == 0)
    {
        int i;
        int sum=0;
        for (i=0;i<=N;i=i+2)
            sum+=i;
        printf("Child sum: %d",sum);
        if (write(fd_result,&sum,sizeof(int))==-1) perror("Error writing to file");
        _exit(0);
    }


    if (id > 0)
    {
        int i;
        int sum=0;
        int sum_odd;
        for (i=1;i<=N;i=i+2)
            sum+=i;
        lseek(fd_result,0,SEEK_SET);
        read(fd_result,&sum_odd,sizeof(int));
        printf("\nThe sum is: %d",sum+(int)sum_odd);
    }

    close(fd_result);
    return 0;
}

请告诉我如何获取子进程的返回值?

Program calculates sum of numbers from 1 to N..
Child process calculates sum of EVEN numbers.
Parent process calculates sum of odd numbers.
I want to get the return value of child process in parent process. How do i do that

#include<stdio.h>
#include<errno.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>

int main()
{
    int N;
    int id;
    int fd_result;;

    printf("Enter N till which you want the sum: \n");
    scanf("%d",&N);
    if ((fd_result=creat("result", 600))== -1)
    {
        perror("Error creating file");
        exit(1);
    }
    if ((fd_result=open("result",O_TRUNC | O_RDWR)) == -1)
    {
        perror("Error Opening file");
        exit(1);
    }
    if ((id=fork())<0)
    {
        perror("Error occurred forking....!");
        exit(errno);
    }
    if (id == 0)
    {
        int i;
        int sum=0;
        for (i=0;i<=N;i=i+2)
            sum+=i;
        printf("Child sum: %d",sum);
        if (write(fd_result,&sum,sizeof(int))==-1) perror("Error writing to file");
        _exit(0);
    }


    if (id > 0)
    {
        int i;
        int sum=0;
        int sum_odd;
        for (i=1;i<=N;i=i+2)
            sum+=i;
        lseek(fd_result,0,SEEK_SET);
        read(fd_result,&sum_odd,sizeof(int));
        printf("\nThe sum is: %d",sum+(int)sum_odd);
    }

    close(fd_result);
    return 0;
}

Pls tell me how do I get the return value of child process?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

当梦初醒 2024-08-25 23:31:08

您正在寻找的是 wait()waitpid()

What you are looking for is wait() or waitpid().

香草可樂 2024-08-25 23:31:08

TLDR

int wstatus;
waitpid(<pid>, &wstatus, 0); // Store proc info into wstatus
int return_value = WEXITSTATUS(wstatus); // Extract return value from wstatus

参考

waitpid 的联机帮助页 显示其类型签名为:

pid_t waitpid(pid_t pid, int *stat_loc, int options);

它还表明我们可以使用 stat_loc 参数存储进程信息:

如果参数stat_loc的值不是空指针,则信息应存储在stat_loc指向的位置

stat_val 参数是 stat_loc 指向的整数值。

然后,我们使用 WEXITSTATUS(wstatus) 从进程中提取返回值。

WEXITSTATUS(stat_val):
如果 WIFEXITED(stat_val) 的值非零,则该宏计算子进程传递给 _exit() 或 exit() 的状态参数的低 8 位,或者子进程的值从 main() 返回。

TLDR

int wstatus;
waitpid(<pid>, &wstatus, 0); // Store proc info into wstatus
int return_value = WEXITSTATUS(wstatus); // Extract return value from wstatus

Reference

The manpage for waitpid shows its type signature is:

pid_t waitpid(pid_t pid, int *stat_loc, int options);

It also states that we can store process information with the stat_loc argument:

if the value of the argument stat_loc is not a null pointer, information shall be stored in the location pointed to by stat_loc

the stat_val argument is the integer value pointed to by stat_loc.

We then use WEXITSTATUS(wstatus) to extract our return value from the process.

WEXITSTATUS(stat_val):
If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().

离旧人 2024-08-25 23:31:08

哎呀!这不是狂欢!不管怎样......

产生一个进程的原因是继续主流,同时做一些不影响它的事情。我正在浏览 10k 图像的目录,&移出重复项。我将比较代码放在一个函数中 &子进程。速度非常快。

获取值的方法是创建一个管道,将一个值回显到该管道上,然后读取该管道:(警告!以下代码可能不起作用,它只是显示一个工作管道)

mkfifo pipe
moved=0
# Use imageMagick 'compare' to find files with zero difference:
comPare () { 
 if [[ ! $(compare -metric AE $1 $2) ]]; then 
    mv $2 moved;
    echo 1 > pipe;
  else echo 0 > pipe
  fi
}

# For every file in the dir, compare it to every other one:
for file1 in $( ls *.bmp | head -n $(( $( ls *.bmp | wc -l) - 1)); do
for file2 in $( ls *.bmp | tail -n $(( $( ls *.bmp | wc -l) - 1)); do
    comPare file1 file2 &
    moved=$(( $(cat pipe) + 1 ))
done
done
rm pipe
echo "Moved $moved files"

到目前为止唯一的问题是我正在使用 USB 驱动器,&权限阻止我创建管道。除此之外...

Oops! This isn't bash! Anyway...

The reason for spawning a process is to continue the main flow, doing something meanwhile that doesn't affect that. I'm running through directories of 10k images, & moving out duplicates. I put the compare code in a function & subprocess that. It's very fast.

The way to get a value back is to create a pipe, echo a value onto that then read the pipe: ( Warning! the following code probably doesn't work, it just shows a working pipe)

mkfifo pipe
moved=0
# Use imageMagick 'compare' to find files with zero difference:
comPare () { 
 if [[ ! $(compare -metric AE $1 $2) ]]; then 
    mv $2 moved;
    echo 1 > pipe;
  else echo 0 > pipe
  fi
}

# For every file in the dir, compare it to every other one:
for file1 in $( ls *.bmp | head -n $(( $( ls *.bmp | wc -l) - 1)); do
for file2 in $( ls *.bmp | tail -n $(( $( ls *.bmp | wc -l) - 1)); do
    comPare file1 file2 &
    moved=$(( $(cat pipe) + 1 ))
done
done
rm pipe
echo "Moved $moved files"

The only problem so far is that I'm working on a usb drive, & permissions are stopping me from creating the pipe. Apart from that ...

深爱不及久伴 2024-08-25 23:31:08

就像 dtmilano 所说,您应该使用 wait 或 waitpid,具体取决于或需要。

但也许你应该将你的程序分成两部分并用 exec 执行子程序。当你 fork 你的子进程接收到 pid 等于 0 时,我不知道你尝试等待 pid 0 的进程信号是否会正常工作。

无论如何,您可以通过退出来传递子进程计算的值,尽管这不是最好的方法。

Like dtmilano said you should use wait or waitpid, depending or need.

But maybe you should split your program in two parts and execute the son with exec. When you make fork your child process receive pid equal 0 and I don't know if you try to wait signals of process with pid 0 will work fine.

Anyway you can pass, though it's not the best way, the value calculated by your child process through exit.

離人涙 2024-08-25 23:31:08

如果您想保留用于表示成功或失败退出状态的返回值,您可以在分叉之前调用 pipe(2) 以在父级和子级之间建立单独的通道。

If you want to preserve the return value for signaling a successful or failure exit status, you can call pipe(2) before forking to set up a separate channel between parent and child.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文