gpt4 book ai didi

c - 父进程不获取子进程返回变量

转载 作者:太空宇宙 更新时间:2023-11-04 02:42:18 24 4
gpt4 key购买 nike

这是一个类,所以我试图理解为什么当子进程返回时没有设置变量 nChars。我读过 waitpid() 获取子进程,但是当我尝试打印 nChars 时,当子进程的 nChars 是命令行字符数时,它仍然显示为零

int main(int argc, char **argv)
{
// set up pipe
int fd[2], status;
pid_t childpid;

pipe(fd);
// call fork()
if((childpid = fork()) == -1){
perror("pipe");
return -1;
}
if (childpid == 0) {
// -- running in child process --
int nChars = 0;
char ch;

close(fd[1]);
// Receive characters from parent process via pipe
// one at a time, and count them.

while(read(fd[0], &ch, 1) == 1)nChars++;

// Return number of characters counted to parent process.
printf("child returns %d\n", nChars);
close(fd[0]);

return nChars;
}
else {
// -- running in parent process --
int nChars = 0;
close(fd[0]);

printf("CS201 - Assignment 3 - \n");

// Send characters from command line arguments starting with
// argv[1] one at a time through pipe to child process.

for(int i=1; i < argc; i++)
write(fd[1], argv[i], strlen(argv[i]));


// Wait for child process to return. Reap child process.
// Receive number of characters counted via the value
// returned when the child process is reaped.

waitpid(childpid, &status, WNOHANG);
printf("child counted %d characters\n", nChars);
close(fd[1]);
return 0;
}

最佳答案

父子不共享内存,所以他们有不同的变量nChars。子项是父项的副本,因此当您更改副本中的某些变量时,它们不会在原始变量中更改。如果您需要从两个执行流程中看到一个变量,请使用线程。

您要从子进程返回 nChars 作为进程退出代码,因此它将位于状态变量中。尝试:

waitpid(childpid, &status, 0);
// removed WNOHANG because with it parent won't wait for child to exit
printf("child counted %d characters\n", status);

但是最好使用管道或套接字等IPC机制在子进程和父进程之间传输数据,因为退出代码是程序退出状态,退出代码0表示一切正常,其他退出代码表示出了问题, 退出代码不是用于传输任意数据

关于c - 父进程不获取子进程返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30549045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com