gpt4 book ai didi

c - FIFO - 从顶层进程读取,从底层进程写入

转载 作者:行者123 更新时间:2023-11-30 17:04:29 25 4
gpt4 key购买 nike

我正在尝试在程序的顶层和底层进程之间进行通信。首先,我创建 FIFO,然后使用 for 循环来 fork n 个进程。在 for 循环内,我检查进程是否为底层进程,如果是,则写入 FIFO。

我对底层进程写入 FIFO 后如何读取 FIFO 感到困惑。如果我尝试在循环之前读取,则循环永远不会执行,因为没有写入任何内容。如果我尝试在循环期间读取代码的父级部分,其他父级也可以读取它。如果我尝试在 for 循环之后读取,则代码循环永远不会完成,因为当最后一个子尝试写入时它会卡住。这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>

#define MAX_BUF 1024

int main(int argc, char **argv){

int numprocs = atoi(argv[1]);
int lev = numprocs;
fprintf(stdout,"ALIVE: Level %d process with pid=%d, child of ppid=%d.\n", lev, getpid(), getppid());
int currpid = getpid();

//create shared memory
const int SIZE = numprocs * sizeof(int);
const char *name = "dleggio1OS";
int shm_fd;
int *ptr;
shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, SIZE);
ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
*ptr = getpid();

//create fifo
int fd;
char *myfifo = "/tmp/dleggio1fifo";
mkfifo(myfifo, 0666);
//read fifo
/*char buff[MAX_BUF];
fd = open(myfifo,O_RDONLY);
read(fd,buff,MAX_BUF);
printf("process %d received %s message.\n",getpid(),buff);
close(fd);*/


//spawn procs
int i;
for(i = 1; i < numprocs; i++){
lev--;
int pfds[2];
char buf[30];
if(pipe(pfds) == -1){
perror("pipe");
exit(1);
}
pid_t pid;


if((pid = fork()) < 0){
perror("fork");
exit(1);
}

if(pid == 0){ //child

ptr[i] = getpid();

close(pfds[1]);
if(read(pfds[0], buf, 3) <= 0){
perror("child");
exit(1);
}
int check = atoi(buf);
fprintf(stdout,"ALIVE: Level %d process with pid=%d, child of ppid=%d.\n", check, ptr[i], ptr[i-1]);

if(check == 1){ //leaf
//write to fifo
fd = open(myfifo, O_WRONLY);
write(fd,"leaf",sizeof("leaf"));
close(fd);
return 0;
}

}
else{ //parent
close(pfds[0]);
char hold[3];
sprintf(hold,"%d",lev);
if(write(pfds[1], hold, 3) <= 0){
perror("parent");
exit(1);
}
//read fifo
/*char buff[MAX_BUF];
fd = open(myfifo,O_RDONLY);
read(fd,buff,MAX_BUF);
printf("process %d received %s message.\n",getpid(),buff);
close(fd);*/

wait(NULL);
return 0;
}
}

//read fifo

/*char buff[MAX_BUF];
fd = open(myfifo,O_RDONLY);
read(fd,buff,MAX_BUF);
printf("received %s message.\n",buff);
close(fd);*/

shm_unlink(name);
unlink(myfifo);
return 0;
}

最佳答案

If I try to read during the loop, in the parent section of the code, other parents can read it as well.

它们都可以从 FIFO 中读取,因为您是在 fork 任何进程之前创建 FIFO 的;因此,他们都使用同一个。如果您希望每个父/子对都有一个只有他们可以使用的私有(private) FIFO,那么您需要将您的 mkfifo() 调用移至循环内部并创建一个 FIFO(具有唯一的名称) ) 对于每个 fork()

关于c - FIFO - 从顶层进程读取,从底层进程写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35758024/

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