23,128
社区成员
发帖
与我相关
我的任务
分享
源代码:
esperantor@ubuntu:~/source$ cat noname_pipe_example.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
pid_t pid;
int temp;
int pipedes[2];
char s[13] = "test message!";
char d[13];
if ((pipe(pipedes))== -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
if ((pid=fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(pid==0)
{
printf("now ,write data to pipe\n");
if ((write(pipedes[1],s,13)) == -1)
{
perror("write");
exit(EXIT_FAILURE);
}
else
{
printf("the written data is :%s\n",s);
exit(EXIT_SUCCESS);
}
}
else if (pid >0)
{
sleep(2);
printf("now,read data from pipe\n");
if ((read(pipedes[0],d,13))==-1)
{
perror("read");
exit(EXIT_FAILURE);
}
printf("the data from pipe is :%s\n",d);
}
return 0;
}
结果:
esperantor@ubuntu:~/source$ gcc -o noname_pipe_example noname_pipe_example.c
esperantor@ubuntu:~/source$ ./noname_pipe_example
now ,write data to pipe
the written data is :test message!
now,read data from pipe
the data from pipe is :test message!test message!
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
pid_t pid;
int temp;
int pipedes[2];
char s[14] = "test message!";//这里数组长度应该为14,包括字符串结速符
char d[13];
if ((pipe(pipedes))== -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
if ((pid=fork()) == -1)
{
perror("fork");
exit(EXIT_FAILURE);
}
else if(pid==0)
{
printf("now ,write data to pipe\n");
if ((write(pipedes[1],s,14)) == -1)//这里长度13改为14
{
perror("write");
exit(EXIT_FAILURE);
}
else
{
printf("the written data is :%s\n",s);
exit(EXIT_SUCCESS);
}
}
else if (pid >0)
{
sleep(2);
printf("now,read data from pipe\n");
if ((read(pipedes[0],d,14))==-1)//这里长度13改为14
{
perror("read");
exit(EXIT_FAILURE);
}
printf("the data from pipe is :%s\n",d);
}
return 0;
}