简体   繁体   English

子进程,fork和exec的内存使用情况

[英]Memory usage by a child process, fork and exec

How can I measure the memory used by a child process after I call fork and exec? 调用fork和exec后,如何测量子进程使用的内存? Basically I want to be able to write code that corresponds to the following 基本上我希望能够编写与以下内容相对应的代码

if (!fork()) {

    // run child process
    exec();
} else {

    while (child active) {
        print memory used by child
    }
}

There are two things that I do not know here, how can I see if the child process has finished running? 我在这里不知道两件事,如何查看子进程是否已完成运行? Will I have to use some sort of process level mutual exclusion here? 我是否需要在这里使用某种过程级互斥? If yes then what is a structure I can use? 如果是,那么我可以使用什么结构? Can I just use the OS filesystem for this purpose? 我可以仅将OS文件系统用于此目的吗?

Also I was looking at the answer at this link Differences between fork and exec , in paragraph 8 the author says copy on write is useful when process calls fork without calling exec. 我也在这个链接上寻找答案, 在fork和exec之间的区别 ,在第8段中,作者说,当进程调用fork而没有调用exec时,写时复制非常有用。 But isn't this true more in the case when the parent calls fork and does not call exec? 但是,在父级调用fork而不调用exec的情况下,这不是真的吗? When the parent calls exec the virtual address space of the child is wiped out and replaced with the one resulting from the new program loaded into memory correct? 当父级调用exec时,子级的虚拟地址空间将被清除,并替换为新程序加载到内存后生成的虚拟地址空间正确吗?

Thank you! 谢谢!

Regarding the above comment chain which I evidently can't reply to because I don't have 50 rep: 关于以上评论链,我显然无法回复,因为我没有50个代表:

The return value of fork in the parent if successful is the PID of the child. 如果成功,则父级中fork的返回值是子级的PID。 You should probably save the return value so you can 您可能应该保存返回值,以便可以
1. wait on the correct child (if you have more than one), and 1.等待正确的孩子(如果您有多个孩子),并且
2. see if fork fails (in which case you probably don't want to loop until the child exits ). 2.查看fork是否失败(在这种情况下,您可能不想在孩子退出之前循环播放)。

You could also use signals to figure out when the child dies instead of continuously trying to wait with the WNOHANG option. 您也可以使用信号来判断孩子何时死亡,而不是连续尝试使用WNOHANG选项等待。 The process will send SIGCHLD to the parent when it terminates (or stops) and if it died then you can wait on it with waitpid and stop your loop. 该进程将在终止(或停止)时将SIGCHLD发送给父进程,如果该进程死亡,则可以使用waitpid等待它并停止循环。 see: 看到:
man 7 signal 男子7信号
man 2 sigaction 男人2 sigaction
for more information on this. 有关更多信息。

regarding memory usage, it seems you either want /proc/[pid]/statm or /proc/[pid]/stat. 关于内存使用情况,您似乎想要/ proc / [pid] / statm或/ proc / [pid] / stat。

man 5 proc will give you all the information about what is in those files. man 5 proc将为您提供有关这些文件中内容的所有信息。

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

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