gpt4 book ai didi

c - 实现匿名管道

转载 作者:行者123 更新时间:2023-11-30 19:49:44 25 4
gpt4 key购买 nike

我正在尝试在不使用系统调用的情况下实现匿名管道:Pipe()、fork()、mkfifo()、open()、read()、write()、close() 。

基本上我用共享内存实现了匿名管道,其中有两个文件描述符(两者都有共享内存ID)一个用于读者,另一个用于作者,通过两个信号量进行通信我唯一没有提到的情况是 fork 的情况。

我的问题是我应该如何实现 fork 调用或者我应该如何处理这种情况。

我可以使用 pthread_atfork() 和 atexit() 系统调用。

非常感谢。

附注

我附上了管道的常规短代码,以准确强调应该如何我的实现工作。

代码有效!!!它只是为了说明我的功能应该如何工作。

    #include<unistd.h>
#include <stdio.h>

int main()
{
int pfd[2], rb;
char buff[100];
//I implemented this syscall by allocating shared memory
if (pipe(pfd)<0)
{
return -1;
}
//here is my problem. I don’t know how to treat this syscall
if (fork())
{

sleep(5);
//I implemented this syscall by two file descriptors which communicate via two
//semaphores
write(pfd[1], "hello world\n", sizeof("hello world\n"));
wait(NULL);
}
else
{
//I implemented this syscall by two file descriptors which communicate via two
//semaphores

rb = read(pfd[0], buff, sizeof(buff));
if (rb < 0)
perror("SON: read");
else
{
printf("SON: writing %d\n", rb);
write(1, buff, rb);
}
}

return 0;
}

真诚的,

伊莱

最佳答案

fork 并不是实现匿名管道所必需的,尽管可能需要测试它。如果您使用的是传统 Unix fork 的平台,那么创建新进程的大多数方法都将涉及 fork 系统调用。您的替代方案是:

  • vfork 紧接着 exec,假设您可以找到您的程序并提供适当的参数;
  • 从外部调用程序的另一个副本;或
  • 线程(pthread_create)。

关于c - 实现匿名管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11326666/

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