逆向 | linux c父子进程通信模板
逆向 | linux c父子进程通信模板
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int main(){
pid_t pid; //parent_id
pid_t cid; //child_pid
printf("Before fork Process id: %d\n", getpid());
int fields[2]; // create pipe
char buffer[1024] = {0};
if(pipe(fields)!=0){
printf("Createpipe error \n");
exit(1);
}
cid = fork();
if(cid==0){ // child
printf("Child process id(my parent id is %d): %d\n", getppid(), getpid());
close(fields[0]);
//char s[] = "from child! \n";
//write(fields[1], s, sizeof(s));
//printf("send ok \n");
// 将子进程的输出由标准输出重定向到 fields 的管道写端上
dup2(fields[1], 1);
// 替换执行脚本
execl("/bin/ls", "ls", "-la", NULL);
exit(0);
}else { // father
printf("Parent process id: %d\n", getpid());
wait(NULL);
printf("ready to recv \n");
int x = read(fields[0], buffer, sizeof(buffer));
printf("recv %d: %s \n",x, buffer);
//close(fields[0]);
}
printf("After fork, Process id: %d\n", getpid());
return 0;
}
本文来自博客园,作者:Mz1,转载请注明原文链接:https://www.cnblogs.com/Mz1-rc/p/18533296
如果有问题可以在下方评论或者email:mzi_mzi@163.com