当前位置: 技术问答>linux和unix
子进程没有正常退出,不清楚什么原因啊
来源: 互联网 发布时间:2016-12-26
本文导语: /************************** * 父进程发送命令给子进程 * *********************/ #include #include #include #include #include static int cmd_handle(int cmd) { if(cmd 256) { printf("child : invaild commadn n"); return -1; } printf("child : the cmd f...
/**************************
* 父进程发送命令给子进程
* *********************/
#include
#include
#include
#include
#include
static int cmd_handle(int cmd)
{
if(cmd 256)
{
printf("child : invaild commadn n");
return -1;
}
printf("child : the cmd from parent is %d n", cmd);
return 0;
}
int main(void)
{
int fd[2];
char *w_buf[4];
char r_buf[4];
pid_t pid;
int cmd;
int child_exit_flag = 0;
memset(r_buf, 0, sizeof(r_buf));
if(pipe(fd) == -1)
{
printf("pipe create error n");
return -1;
}
if((pid = fork()) == 0)
{
close(fd[1]);
while(!child_exit_flag)
{
read(fd[0], r_buf, 4);
printf("child : receive r_buf : %s n", r_buf);
cmd = atoi(r_buf);
if(cmd == 0)
{
printf("child : receive cmd from parent over n now child exit n");
child_exit_flag = 1;
}
else if(cmd_handle(cmd) != 0)
break;
sleep(1);
}
close(fd[0]);
printf("child ready to exit n");
exit(0);
}
else if(pid > 0)
{
int i = 0;
close(fd[0]);
w_buf[0] = "003";
w_buf[1] = "005";
w_buf[2] = "777";
w_buf[3] = "000";
for(; i