gpt4 book ai didi

C - 使用 fork() 和 exec() 两次

转载 作者:IT王子 更新时间:2023-10-29 00:31:29 26 4
gpt4 key购买 nike

我有以下代码:

int main(int argc, char **argv)
{
char *program;
char stringa[1000] = "";
int num = 123;
char snum[10];

if (argc != 2) {
printf("Usage: mon fileName\n where fileName is an executable file.\n");
exit(-1);
} else {
program = argv[1];
sprintf(stringa, "./%s", program);

pid_t pid = fork();
if (pid < 0 ) {
perror("fork failed.");
exit(1); }

else if (pid == 0) {
char* args[] = {stringa, NULL};
execv(args[0], args);
}
else {

char procmon_str[] = "./procmon";
num = pid;
sprintf(snum, "%d",num);
pid_t pid2 = fork();
if (pid2 == 0) {
char* args2[] = {procmon_str, snum, NULL};
execv(args2[0], args2); }
else {

printf("PID of child is %s", snum);
int parent_pid = getpid();
printf("PID of parent is %d", parent_pid);}

}}
wait(NULL);

return 0;
}

这个程序的名字是myProgram .我在 shell 中提供的参数是:

./myProgram calc

calc是我想使用 myProgram 启动的另一个程序. myProgram然后执行 calc , 取其 PID并通过 PID到另一个名为 procmon 的程序用它做点什么;这就是为什么我需要 fork 两次。但是,当我运行上面的代码时,我得到:

procmon: cannot open /proc/6225/stat, the monitored process is not running anymore .

我该如何解决这个问题?

什么是calc做什么?它进入 for循环,递增一个 int可变并进入休眠状态 3 秒并重复 10 次。所以它应该运行大约 30 秒。

什么是procmon做什么? procmon只收到 PID一个进程作为参数并显示相应的 /proc/PID/stat文件。当您单独运行它时,它会完美运行。

最佳答案

您有竞争条件。您无法保证第一个 fork() 实际上甚至在 calc 子进程完成执行并退出之前返回到您的父进程。您需要同步流程的执行。

关于阻塞和信号位置的 ETA 建议

if (pid == 0) 
{
// block here waiting for the go-ahead from parent
char* args[] = { stringa, NULL };
execv( args[ 0 ], args );
}

......

else
{
// signal calc child here
printf( "PID of child is %s", snum );
int parent_pid = getpid();
printf( "PID of parent is %d", parent_pid );
}

学习如何通过进程间通信阻塞和发出信号留给提问者作为练习。

关于C - 使用 fork() 和 exec() 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com