如何在 C 编程中执行 Shell 脚本、接收反馈和处理器 ID,以及关闭进程

How to Execute Shell Script in C Programming, Receive Feedback and Processor ID, and Close Process

我正在编写一个程序,需要启动另一个程序几秒钟,然后关闭它。

如果可能,程序控制台的反馈会很有用。

我想我会通过从子进程中检索 pid 和 运行 pkill 来关闭程序?

解决此问题的最佳方法是什么?

提前致谢

OP 编辑​​

void mountAd(char* adFilePath){

    char* mountPoint = getNextAvailableMount();

    // Set Playlist ready to be played
    editPlaylist(mountPoint, adFilePath);

    // Fork process and fire up ezstream
    int pid = fork();

    if(pid == 0){
        puts ("Child Process Here\n");
        execl ("/usr/local/bin/ezstream","/usr/local/bin/ezstream", "-c", "/home/hearme/radio/_test_adverts/advert01.xml", NULL);
        perror("execl");

    } else {
        puts ("Parent Process Here\n");
    }

    // Advised sleep for 3 seconds until ezstream has started
    sleep(3);

    // More stuff to do here later

    kill(pid, SIGTERM);
    waitpid(pid, NULL, 0);

}

像这样的东西应该可以工作:

pid = fork();
if (pid < 0)
    /* fork failed, error handling here */

if (pid == 0) {
    /* we are the child, exec process */
    execl(...);

    /* this is only reached if execl fails */
    perror("execl");

    /* do not use exit() here, do not return from main() */
    _Exit(EXIT_FAILURE);
}

/* we are the parent */
sleep(duration);

kill(pid, SIGKILL);

/* use wait/waitpid/waitid as needed */
waitpid(pid, NULL, 0);

请注意,当无法找到或执行您想要 运行 的程序时,这不会正确执行错误检查,对于这种情况需要更详细的方案,如果您有兴趣,我可以详细点。