如何让孩子PID用C? [英] How to get child PID in C?

查看:140
本文介绍了如何让孩子PID用C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 -loop创建一个子进程。里面的子过程中,我可以检索 GETPID孩子PID()

然而,由于某些原因,当我试图 GETPID()的值存储到由父进程声明的变量,改变是,当我检查它无效在父进程。我假定这是与某种过程变量范围的事。没有真正熟悉C,所以不能太肯定。

总之是什么 GETPID()孩子PID(从子进程调用时)的结果存储到一个变量在父进程的一种方式?

或者,也许另一种方法是存储叉()进入父的变量,并呼吁该变量的一些函数来获取孩子的PID?我不知道如何可以做到这一点,所以如果这是更好的方法,你会怎么做呢?


解决方案

已返回子的PID。只是存储返回值。

看男子2叉:


  

返回值

 成功完成后,fork()的值0返回子进程
 返回子进程的父进程的进程ID。否则,一个
 -1值返回给父进程,没有创建子进程,并
 全局变量errno设置为指示的错误。


I'm creating child processes in a for-loop. Inside the child process, I can retrieve the child PID with getpid().

However, for some reason when I try to store the value of getpid() into a variable declared by the parent process, the change is nullified when I check for it in the parent process. I'm assuming this has to do with some sort of process variable scope. Not really familiar with C, so can't be too sure.

Anyhow what is a way of storing the result of getpid() of a child PID (when called from the child process) into a variable in the parent process?

Or maybe another approach is storing fork() into a variable in the parent and calling some function on that variable to retrieve the child's PID? I don't know how to do this either, so if this is the better way, how would you do this?

解决方案

fork already returns the child's pid. Just store the return value.

look at man 2 fork:

RETURN VALUES

 Upon successful completion, fork() returns a value of 0 to the child process and
 returns the process ID of the child process to the parent process.  Otherwise, a
 value of -1 is returned to the parent process, no child process is created, and
 the global variable errno is set to indicate the error.

这篇关于如何让孩子PID用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆