简体   繁体   English

在linux中使用父进程和子进程中的Pipe

[英]Using Pipe in parent and child process in linux

I write a code for pipe in that every time parent die first why it happen there is no rule which process execute first but here parent always die first why, anybody can explain this code. 我写了一个管道代码,因为每次父亲为什么会先发生这种情况,没有规则哪个进程首先执行,但这里父亲总是先死,为什么,任何人都可以解释这个代码。

main() { main(){

int data_pass;
int file_pipes[2];
const char *some_data = "my name is khan";
char buffer[BUFSIZ + 1];
pid_t pid;
memset(buffer,'\0',BUFSIZ);
if(pipe(file_pipes) == 0)
{
    pid = fork();
    switch(pid)
    {

        case -1:
        {
            printf("cant create \n");
            exit(0);
        }
        case 0:
        {
            data_pass = read(file_pipes[0],buffer,BUFSIZ);
            printf("readed data is %s\n",buffer);
            exit(0);
        }
        default:
            {

            sleep(5);
            data_pass = write(file_pipes[1],some_data,strlen(some_data));
            printf("wrote\n");
        }
    }
}
exit(0);

} }

o/p-> wrote o / p->写道

 readed data is my name is khan

It depends on scheduler. 这取决于调度程序。 On some systems child is created in runnable state, but parent can use his whole time quantum. 在某些系统上,child是在runnable状态下创建的,但是parent可以使用他的整个时间量。 On some other system can be implementation different and parent is stopped and child is chosen to run instantly. 在其他一些系统上可以实现不同的,父节点被停止,子节点被选中立即运行。

In conclusion you can not rely on execution order of processes that are runnign in parallel without synchronization. 总之,您不能依赖于没有同步并行运行的进程的执行顺序。

See syscall waitpid or wait . 请参阅syscall waitpid等待

Also sleep(5) doesn't mean the process will be sleeping for 5 seconds. 睡眠(5)并不意味着该过程将睡眠5秒。 It can be more if scheduler plans other processes with higher priority instead. 如果调度程序计划具有更高优先级的其他进程,则可以更多。 It can be less too, if process obtains signal from OS. 如果进程从OS获得信号,它也可以更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM