
C语言创建管道
要求用C语言创建一个管道,父进程创建一个子进程,子进程向管道写一个字符串“safasfsa”,父进程从管道读出该字符串,并打印出来偶C语言小白来着,求高手帮忙,,,。。。...
要求用C语言创建一个管道,父进程创建一个子进程,子进程向管道写一个字符串“safasfsa”,父进程从管道读出该字符串,并打印出来
偶C语言小白来着,求高手帮忙,,,。。。急急急! 展开
偶C语言小白来着,求高手帮忙,,,。。。急急急! 展开
推荐于2016-11-10
展开全部
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main(int argc,char *argv[])
{
int pd[2];/*用于保存管道文件描述符*/
char out[80],str[]="safasfsa";/*str是要写入的字符串,out用于保存从管道读取的字符串*/
assert(pipe(pd)!=-1);/*断言用于确定pipe()函数执行成功,如果管道创建失败,则pipe()返回-1*/
if (!fork()) write(pd[1],str,strlen(str));/*创建子进程,并将字符串写入管道*/
else {
read(pd[0],out,strlen(str));/*在主进程中从管道中读取子进程写入的字符串*/
printf("%s\n",out);/*主进程中输出。*/
}
return 0;
}
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main(int argc,char *argv[])
{
int pd[2];/*用于保存管道文件描述符*/
char out[80],str[]="safasfsa";/*str是要写入的字符串,out用于保存从管道读取的字符串*/
assert(pipe(pd)!=-1);/*断言用于确定pipe()函数执行成功,如果管道创建失败,则pipe()返回-1*/
if (!fork()) write(pd[1],str,strlen(str));/*创建子进程,并将字符串写入管道*/
else {
read(pd[0],out,strlen(str));/*在主进程中从管道中读取子进程写入的字符串*/
printf("%s\n",out);/*主进程中输出。*/
}
return 0;
}
参考资料: 测试环境:UBUNTU+GCC4.2.4
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询