C: 'run' 命令使用 waitpid & 命令行输入

标签 c waitpid

作为我的代码的一部分,我正在尝试编写一个函数,以便用户可以键入

shell> run date     //Line of user input
Mon Jan 19 11:51:57 EST 2009  //Printed by program
shell: process 348 exited normally with status 0

用户只需键入“运行日期”,程序就会显示底部的两行。 到目前为止,这是我在我的职能中所拥有的..

 else if(strcmp(argv[1],"run") == 0 ) {
           if ((pid = fork()) < 0) {  //Child process fork
                    perror("fork");       
                    exit(1);
                    }   
            //printf("ok");
            if (pid == 0) {  //Child executes code
                    execvp(argv[2], &argv[2]); 
                    exit(1);
                    }

    waitpid(atoi(argv[2]), &status, WNOHANG);

    printf("shell: run status is %d\n", status);
    }

这还没有产生,但我想知道到目前为止这是否正确以及我是否遗漏了重要的部分!谢谢。

最佳答案

waitpid 的第一个参数应该是 child 的 PID。另外,请注意 WNOHANG 选项可防止调用进程被阻塞;因此,如果预期进程的状态信息不可用,waitpid 将返回 0。如果您想等到 child 终止,请使用 0 作为 waitpid 的第三个参数(或使用 wait 而不是 waitpid )。

关于C: 'run' 命令使用 waitpid & 命令行输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896536/

相关文章:

c - 为什么我的 C 代码中的 pipe() 不断返回 -1

c - 在 C 中获取文件大小的正确方法

c - waitpid 用法错误?

c - 无法让 waitpid() 返回正确的 WEXITSTATUS 错误情况

c - Unix-Waitpid 'status'

C - 使用 fork() 创建 3 个子进程

perl - 如何在不杀死 child 的情况下超时waitpid?

C ANSI 转义码

c - fifo 循环队列中的 pthread_cond_wait 死锁

c - Lex 和 yacc - 无法编译 y.tab.c 文件