等待系统调用完成

Waiting for system call to finish

我的任务是创建一个程序,该程序将包含程序列表的文本文件作为输入。然后它需要 运行 对程序进行 valgrind(一次一个),直到 valgrind 结束或直到程序达到最大分配时间。我让程序做我需要它做的一切,除了它不等待 valgrind 完成。我使用的代码格式如下:

//code up to this point is working properly
pid_t pid = fork();
if(pid == 0){
    string s = "sudo valgrind --*options omitted*" + testPath + " &>" + outPath;
    system(s.c_str());
    exit(0);
}
//code after here seems to also be working properly

我 运行 遇到一个问题,child 只是调用系统并继续前进,而不等待 valgrind 完成。因此,我猜测该系统不适合使用,但我不知道我应该拨打什么电话。谁能告诉我如何让 child 等待 valgrind 完成?

我认为您正在寻找 fork/execv。这是一个例子:

http://www.cs.ecu.edu/karl/4630/spr01/example1.html

另一种选择可能是 popen。

您可以 forkexec 您的程序,然后等待它完成。请参阅以下示例。

pid_t pid = vfork();
if(pid == -1)
{
    perror("fork() failed");
    return -1;
}
else if(pid == 0)
{
    char *args[] = {"/bin/sleep", "5", (char *)0};
    execv("/bin/sleep", args);  
}

int child_status;
int child_pid = wait(&child_status);
printf("Child %u finished with status %d\n", child_pid, child_status);