gpt4 book ai didi

c - 管道中父进程的 wait() 有什么问题

转载 作者:行者123 更新时间:2023-11-30 14:34:40 25 4
gpt4 key购买 nike

有人问我:

  1. 下面的代码有什么问题?
  2. 如何在儿子的流程代码中修复它:
#define BUF_SIZE 4096
int my_pipe[2];
pipe(my_pipe);
char buf[BUF_SIZE];
int status = fork();

//Filled buf with message...
if (status == 0) { /* son process */
close(my_pipe[0]);
write(my_pipe[1],buf,BUF_SIZE*sizeof(char));
exit(0);
}
else { /* father process */
close(my_pipe[1]);
wait(&status); /* wait until son process finishes */
read(my_pipe[0], buf, BUF_SIZE*sizeof(char));
printf("Got from pipe: %s\n", father_buff);
exit(0);
}
}

所以我想出了下一个代码来尝试解决这个问题:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

#define BUF_SIZE 6

int main() {
int my_pipe[2];
pipe(my_pipe);

char buf[BUF_SIZE];
int status = fork();
//Filled buf with message...
for (int i = 0; i < BUF_SIZE; i++) buf[i] = 'a';

if (status == 0) { /* son process */
close(my_pipe[0]);
write(my_pipe[1], buf, BUF_SIZE * sizeof(char));
_exit(0);
} else { /* father process */
close(my_pipe[1]);
wait(&status); /* wait until son process finishes */
printf("Son Status: %d\n", status);
read(my_pipe[0], buf, BUF_SIZE * sizeof(char));
printf("Got from pipe: %s\n", buf);
_exit(0);
}
}

我的第一个想法是 wait(&status) 有问题,如果子进程无法完成,这可能会导致程序无法终止。

在儿子的代码中,我相信如果管道中没有足够的空间,write 将阻塞进程,从而阻塞整个应用程序。

如果我的主张是正确的,我该如何证明呢?而且我不知道如何修复儿子的代码。

最佳答案

您对管道大小的假设是正确的,我可以使用 BUF_SIZE0x10000 重现该问题。

但解决方案不在客户这边,而在家长那边。您只需在 wait() 之前执行 read(),当然您应该始终使用返回代码来确定您收到了多少。父级的此修复不再导致阻塞:

    len = read(my_pipe[0], buf, BUF_SIZE * sizeof(char));
if( len >= 0 ) {
printf("Got %d from pipe\n", len );
} else {
perror( "read()" );
}
close(my_pipe[1]);
wait(&status); /* wait until son process finishes */
printf("Son Status: %d\n", status);

在子进程中,您可以使用 fcntl(my_pipe[1], F_SETFL, O_NONBLOCK); 使用非阻塞 IO,因此 write() 会发送尽可能多的数据可能然后返回。当然,在这种情况下其余数据将会丢失。

关于c - 管道中父进程的 wait() 有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58877140/

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