一,用管道进行父子进程通信
代码:
#include<unistd.h>
#include<stdio.h>
#define MAXLINE 120
#define MSGINFO "hurry up !\n"
int main(void)
{
int fd[2];
int result;
char msg[MAXLINE+1]={'\0'};
pid_t pid;
if(pipe(fd)<0)
{
printf("create pipe failed !");
}
if((pid=fork())<0)
{
printf("fork child proc failed!\n");
}
if(pid > 0) //father
{
//close(fd[0]);
if(dup2(fd[1], STDOUT_FILENO)<0)
{
printf("dup2 error !\n");
}
write(STDOUT_FILENO, MSGINFO, strlen(MSGINFO));
}
else //chilld
{
//close(fd[1]);
if(dup2(fd[0], STDIN_FILENO) < 0)
{
printf("dup2 error in child proc !");
}
read(STDIN_FILENO, msg, MAXLINE);
printf("get msg:%s \n", msg);
}
return 0;
}
执行结果:
get msg:hurry up !
二,popen和pcloseh函数
popen启动一个shell进程,并执行输入的命令,把执行结果通过FILE输出
代码:
#include<unistd.h>
#include<stdio.h>
#define MAXLINE 120
int main(void)
{
char text[MAXLINE]={'\0'};
FILE *fin;
if((fin = popen("more /tmp/text.txt", "r"))<0)
{
printf("error in popen !\n");
}
while(1)
{
if(fgets(text, MAXLINE, fin) == NULL)
{
break;
}
fputs(">>", stdout);
fputs(text, stdout);
}
if(pclose(fin) == -1)
{
printf("pclose err !");
}
return 0;
}
执行结果:
>>how areyou ?
>>fine,and you?
>>fine too.
>>