阅读背景:

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

来源:互联网 

I have the following code:

我有以下代码:

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;
}
int mai



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: