Waiting for system call to finish

人盡茶涼 提交于 2021-02-10 20:37:16

问题


I've been tasked to create a program that takes a text file that contains a list of programs as input. It then needs to run valgrind on the programs (one at a time) until valgrind ends or until the program hits a max allotted time. I have the program doing everything I need it to do EXCEPT it isn't waiting for valgrind to finish. The code I'm using has this format:

//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

I'm running into an issue where the child just calls the system and moves on without waiting for valgrind to finish. As such I'm guessing that system isn't the right call to use, but I don't know what call I should be making. Can anyone tell me how to get the child to wait for valgrind to finish?


回答1:


I think that you are looking for fork/execv. Here is an example:

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

An other alternative could be popen.




回答2:


You can fork and exec your program and then wait for it to finish. See the following example.

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);


来源:https://stackoverflow.com/questions/30623063/waiting-for-system-call-to-finish

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!