gpt4 book ai didi

c - 使用dup,pipe,fifo与子进程通信

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

我正在尝试一个示例程序,通过两个进程使用 fork() 从文件开头读取数据。

当fork()被调用时,内核创建一个子进程,这个子进程继承了父进程的属性。所有打开的文件和文件描述符。我的目标是让 child 和 parent 从头开始阅读文件。我尝试使用 dup2() 创建单独的描述符,但它不起作用。

我的第二个问题是有什么办法可以让子进程在完成初始任务后继续处理另一个任务。 (必须将信号发送给父级以请求另一项任务?父级将通过管道或 fifo 与子级通信)

 int main(int argc, char* argv[]){
int fd1,fd2;
int fd;
int read_bytes;
pid_t pid;
char* buff;

buff = malloc(sizeof(buff)*5);
if(argc < 2){
perror("\nargc: Forgot ip file");
return 1;
}

fd = open(argv[1],O_RDONLY);
if(-1 == fd){
perror("\nfd: ");
return 2;
}
pid = fork();
if(pid == -1){
perror("\n pid");
return 1;
}
else if(pid == 0){ // CHILD
dup2(fd1,fd);
read_bytes = read(fd1,buff,5);
printf("\n %s \n",buff);
}
else{ //PARENT
wait();
printf("\n Parent \n");
dup2(fd2,fd);
//close(fd);
read_bytes = read(fd2,buff,5);
printf("\n %s \n",buff);
}
return 0;
}

请帮忙理解

最佳答案

(1) 正如 loreb 在评论中提到的,dup2 复制 文件描述符。来自 man (2) dup2 的智慧:

After a successful return from one of these system calls, the old and new file descriptors may be used interchangeably. They refer to the same open file description (see open(2)) and thus share file offset and file status flags; for example, if the file offset is modified by using lseek(2) on one of the descriptors, the offset is also changed for the other.

所以你得出了一个错误的假设。只需在 child 中第二次关闭并打开文件。

(2) dup2 签名是int dup2(int oldfd, int newfd)。您正在执行 dup2(fd1, fd),但 fd 是您要复制的描述符,因此您需要反转参数。

(3) 局部变量没有被初始化所以

int fd1,fd2;

具有随机值。当您执行 dup2(fd1, fd) 时,您正在尝试使用 fd1 中的任何随机值,如果它(通常)大于 1023 将导致调用失败并显示 EBADF。

(4) wait() 接受一个参数,所以它至少应该是 wait(NULL)

(5) 始终 检查系统调用的返回值。您的 dupread 等几乎肯定会失败。

我会建议让它发挥作用,然后将您的第二个问题作为单独的帖子提交。

关于c - 使用dup,pipe,fifo与子进程通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18600559/

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