【问题标题】:Program fails to execute statement程序执行语句失败
【发布时间】:2012-08-31 04:08:39
【问题描述】:

我非常了解 C 编程,但我对 Unix 系统调用没有太多经验。很长一段时间后,我正在重新探索我的 Unix 知识。所以我从 fork 和 execlp 系统调用开始。我正在 ubuntu_linux 上练习示例。

这是一个教科书示例程序,它接受来自 STD_IN 的命令并在子进程中执行它。

int main (int argc, char *argv[]) {
   char command[MAX_LINE];
   pid_t pid;
   int   status;

   printf ("%% ");
   while (fgets (command,MAX_LINE,stdin ) != NULL){
        if (command[strlen(command)-1] == '\n')
          command[strlen(command)-1] = '\0';

        if ((pid=fork ()) < 0) {
           perror ("fork failed :  \n");
        }

        if (pid == 0) {
           printf (" I am child and my PID is %d",getpid ());
           execlp (command, command, (char *)0);
           perror ("couldn't execute:"); 
           exit(127);
        }

        printf (" I am parent and my PID is %d\n ",getpid ());
        if ((pid = waitpid (pid, &status, 0)) < 0){
            perror("waitpid error\n");
        }

        printf ("%% ");
    }
    exit (0);
}

我放了一些printf statments,但是当命令成功执行时,程序没有打印 "I am child and my PID is" 行。但是,如果输入命令不正确并且失败,它会打印上面的行。

我希望在这两种情况下都会打印该行,因为打印语句在 execlp 之前。

【问题讨论】:

  • 你可能想在 execlp 之前刷新你的 printf,即 fflush(stdout) 看看你得到了什么。
  • 为什么你总是打印错误并强迫你的孩子退出失败?
  • @ApprenticeQueue:我知道 fflush 会解决这个问题。但是程序正在显示 printf 之后的 perror 输出。在这里,stdout 和 stderr 都只指向控制台。
  • @Sachin,标准错误已自动刷新。但是 stdout 不会自动刷新,并且在您调用 exit 时会被刷新。
  • 如果你不打印换行符,你的输出不会被刷新。特别是在调试时,“总是”在任何诊断输出的末尾打印一个换行符。或者,也可以使用fflush() 来增加保证。

标签: c unix system-calls


【解决方案1】:

这应该在执行之前刷新标准输出。

printf (" I am child and my PID is %d",getpid ());
fflush(stdout);
execlp (command, command, (char *)0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-16
    • 2011-12-10
    • 1970-01-01
    • 2019-02-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    相关资源
    最近更新 更多