我试图理解命令pipe(2)
,例如:
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
我想获得两个带有 , 的文件描述符shared memory
,用于匿名管道(父子关系)。
例如,这是父子进程之间的简单对话:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#define SHMSIZE 16
int main() {
int shmid;
char *shm;
if(fork() == 0) // child first
{
shmid = shmget(2009, SHMSIZE, 0);
shm = shmat(shmid, 0, 0);
char *s = (char *) shm;
*s = '\0';
int i;
// child enters the input that would be stored in the shared memory
for(i=0; i<3; i++) {
int n;
printf("Enter number<%i>: ", i);
scanf("%d", &n);
// convert the input into a c-string
sprintf(s, "%s%d", s, n);
}
strcat(s, "\n");
// display the contents of the shared memory
printf ("I'm the child process , and I wrote:%s\n",shm);
// detaches the shared memory segment
shmdt(shm);
}
else // parent
{
// get the segment
shmid = shmget(2009, SHMSIZE, 0666 | IPC_CREAT);
// attaching the segment to the father
shm = shmat(shmid, 0, 0);
// father waits for the son the finish
wait(NULL);
// father displays what the son wrote
printf ("I'm the father , and my child wrote :%s\n",shm) ;
// detaches the shared memory segment
shmdt(shm);
shmctl(shmid, IPC_RMID, NULL);
}
return 0;
}
输出非常简单:
Enter number<0>: 123
Enter number<1>: 567
Enter number<2>: 789
I'm the child process , and I wrote:123567789
I'm the father , and my child wrote :123567789
这是我的实现shm_pipe_pipe()
,替换为pipe(2)
:
int shm_pipe_pipe(int spd[2])
{
spd[0] = shmget(2009, SHMSIZE, 0);
spd[1] = shmget(2009, SHMSIZE, 0666 | IPC_CREAT);
if (spd[0] == -1 || spd[1] == -1)
return -1;
return 1;
}
我的问题是:
我知道那
fd[0]
是用来阅读和fd[1]
写作的,但它们到底是什么?地址?我上面写的功能
shm_pipe_pipe
似乎不起作用,它有什么问题?
谢谢`