23,121
社区成员
发帖
与我相关
我的任务
分享
// B程序 使用pipe ,测试程序
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
static int flag = 0;
int main()
{
char output[128] = {0};
int fd[2];
int pid;
int *status;
pipe(fd);
/*为了让下面的READ不阻塞 并判断waitpid*/
int flag = fcntl(fd[0], F_GETFL, 0);
flag |= O_NONBLOCK;
if(fcntl(fd[0], F_SETFL, flag) < 0)
{
perror("fcntl");
return -1;
}
if((pid = fork()) > 0)
{//父进程可以waitpid来等待子进程结束, 所以把读放在父进程里, ping 命令程序放在子进程里
while(1)
{
while(read(fd[0], output, 128) == 128)
if(strlen(output) != 0)
{//这里为了调试 不出现满屏的"parent Process output : "
printf("parent Process output : %s\n", output); //这里调试是输出来,如果是我的程序里,就是把output发送给程序A
memset(output,0, sizeof(output));
}
if(waitpid(pid, status, WNOHANG) == pid)
//if(WIFEXITED(status) !=0 || WIFSIGNALED(status))
{//如果不阻塞方式 等待子进程退出成功, 就退出
printf("----fir = %d -- sec = %d----\n",WIFEXITED(status), WIFSIGNALED(status));
printf("Process parent exit\n");
exit(0);
}
}
}
else
{
//将ping 命令所有输出重定向到 写管道
dup2(fd[1], STDOUT_FILENO);
dup2(fd[1], STDERR_FILENO);
printf("Oh my buf where...\n");
printf("Oh my buf where...\n");
// **** 省略无数个printf...
sleep(5); //问题1: 不管怎么弄, 反正都是等待5秒后 父进程才能读到数据. WHY? 还有优先顺序?
//问题2: 父进程, 根本不按顺序输出, 那A进程怎么接收咯, SHIT
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
/* no error check at all */
int main(int argc, char* argv[])
{
int m_pipe[2];
pid_t pid;
pipe(m_pipe);
if ((pid = fork()) > 0) //parent
{
char ping_out[100];
int nbytes = 0;
close(m_pipe[1]);
while ((nbytes = read(m_pipe[0], ping_out, 100)) != 0)
{
write(STDOUT_FILENO, ping_out, nbytes);
}
close(m_pipe[0]);
wait(NULL);
}
else if (pid == 0) //child
{
dup2(m_pipe[1], STDOUT_FILENO);
dup2(m_pipe[1], STDERR_FILENO);
close(m_pipe[0]);
char command[100];
sprintf(command, "ping -c 4 %s", argv[1]);
execl("/bin/bash", "sh", "-c", command, NULL);
exit(127); //execl error , or never reach here
}
else
{
fprintf(stderr, "fork error\n");
exit(1);
}
return 0;
}