一段代码中要执行两个程序,而且后边的要等待前面的执行结束。在这种情况下使用文件锁并不是很好的方式。 这样会把“上锁”和“解锁”这两个步骤写在不同的位置,降低可读性,使程序不容易维护。写程序的时候要坚持 “低耦合,高内聚”的宗旨。所以在这种情况下,使用简单的 fork 和 waitpid 就可以很好的解决这个问题。

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/time.h>

int main(void)
{
    pid_t pid;
    int m;
    int status;

    if ((pid = fork()) < 0)
        printf("fork error!");
    else if (pid == 0)
    {
        execl("/bin/ps", "ps", "-a", "-u", "-x", (char *)0);
        exit(0);                      /* 子进程在这里该退出了,后面的waitpid应该在父进程里执行 */
    }
    if (waitpid(pid, &status, 0) < 0)
        printf("waitpid error.");
    if (WIFEXITED(status))
		printf("\n\n\nin parent exited with status %d\n", WEXITSTATUS(status));
    return 0;
}

还有一个例子可以看 linux-3.4.11/tools/power/cpupower/utils/idle_monitor/cpupower-monitor.c +272 处。

子进程的结束状态返回后存于status,底下有几个宏可判别结束情况

WIFEXITED(status)如果子进程正常结束则为非0值。
WEXITSTATUS(status)取得子进程exit()返回的结束代码,一般会先用WIFEXITED 来判断是否正常结束才能使用此宏。
WIFSIGNALED(status)如果子进程是因为信号而结束则此宏值为真
WTERMSIG(status)取得子进程因信号而中止的信号代码,一般会先用WIFSIGNALED 来判断后才使用此宏。
WIFSTOPPED(status)如果子进程处于暂停执行情况则此宏值为真。一般只有使用WUNTRACED 时才会有此情况。
WSTOPSIG(status)取得引发子进程暂停的信号代码,