【问题标题】:Parent Process Waiting for Child to Finish in C父进程等待子进程在 C 中完成
【发布时间】:2013-09-18 16:34:13
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define MAX_LINE 80 /* 80 chars per line, per command, should be enough. */

/**
 * setup() reads in the next command line, separating it into distinct tokens
 * using whitespace as delimiters. It also sets the args parameter as a 
 * null-terminated string.
 */

void setup(char inputBuffer[], char *args[],int *background)
{
    int length, /* Number  of characters in the command line */
        i,      /* Loop index for inputBuffer array */
        start,  /* Index where beginning of next command parameter is */
        ct;     /* Index of where to place the next parameter into args[] */

    ct = 0;

    /* Read what the user enters on the command line */
    length = read(STDIN_FILENO, inputBuffer, MAX_LINE);  

    start = -1;
    if (length == 0)
        exit(0);            /* ^d was entered, end of user command stream */
    if (length < 0){
        perror("error reading command");
    exit(-1);           /* terminate with error code of -1 */
    }

    /* Examine every character in the inputBuffer */
    for (i = 0; i < length; i++) { 
        switch (inputBuffer[i]){
        case ' ':
        case '\t' :               /* argument separators */
            if(start != -1){
                args[ct] = &inputBuffer[start];    /* set up pointer */
                ct++;
            }
            inputBuffer[i] = '\0'; /* add a null char; make a C string */
            start = -1;
            break;

        case '\n':                 /* should be the final char examined */
            if (start != -1){
                args[ct] = &inputBuffer[start];     
                ct++;
            }
            inputBuffer[i] = '\0';
            args[ct] = NULL; /* no more arguments to this command */
            break;

        case '&':
            *background = 1;
            inputBuffer[i] = '\0';
            break;

        default :             /* some other character */
            if (start == -1)
                start = i;
    } 
    }    
    args[ct] = NULL; /* just in case the input line was > 80 */
} 

int main(void)
{
    char inputBuffer[MAX_LINE]; /* Buffer to hold the command entered */
    int background;             /* Equals 1 if a command is followed by '&' */
    char *args[MAX_LINE/2+1];/* Command line (of 80) has max of 40 arguments */


    while (1){            /* program terminates normally inside setup */
    background = 0;
    printf("CSE2431Sh->");
        fflush(0);
        setup(inputBuffer, args, &background);       /* get next command */

    /* the steps are:
     (1) fork a child process using fork()
     (2) the child process will invoke execvp()
     (3) if background == 0, the parent will wait, 
        otherwise returns to the setup() function. */

          /* MY CODE HERE */
          pid_t pid;

        pid = fork();

        if(pid == 0)
        {
                execvp(args[0],args);
                /* If execvp returns, it must have failed. */

                printf("Fork Failed\n");
                exit(0);
        }
        else
        {
                if(&background == 0)
                {
                        while( wait(&background) != pid)
                        {/* Do nothing, waiting */}
                }
                else
                {
                        setup(inputBuffer, args, &background);
                }
       }
   }
}

我正在尝试分叉一个子进程,让子进程调用 execvp() 并让父进程在后台等待。我的错误来自与父代码的等待部分。上面写着我的代码的所有内容都已给出,不应编辑

【问题讨论】:

  • 您的if(&amp;background == 0) 将始终失败,因为background 的地址不是0
  • 附带说明,在 *nix 上不存在以负状态码退出的情况。通常它是使用的至少 8 位的无符号值(不确定这是否是通用的),因此使用 -1 退出实际上会返回 255。
  • 如果 execv 失败,为什么将“fork failed”打印到错误的流中?试试perror( "execvp" )

标签: c


【解决方案1】:
if(&background == 0)
   ^

那条线没有多大意义。当您可能想要比较实际存储的值时,您正在比较地址,即您可能希望删除&amp;

否则test永远不会为真,即变量background的地址永远不会为0。

【讨论】:

    【解决方案2】:

    您的“分叉失败”消息应该是“执行失败”(分叉有效;执行失败)。你还应该有一个单独的“fork failed”错误报告,但你现在错过了。并且错误消息应该写到stderr,而不是stdout

    wait() 循环条件应该是:

    int corpse;
    int status;
    while ((corpse = wait(&status)) != -1 && corpse != pid)
        ;
    

    调试时,在每次迭代时打印来自wait() 的信息。请注意,waitpid() 允许您在有尸体要收集时等待,但如果没有死去的孩子要哀悼,则返回。

    所有这些只有在你处理了你应该从编译器得到的警告之后才有意义。如果您没有收到关于if (&amp;background == 0) 始终为假的警告,您需要调高编译器警告级别。如果你使用 GCC,gcc -Wall 是一个好的开始,gcc -Wall -Wextra -Wstrict-prototypes -Wmissing-prototypes 更好。并修复来自编译器的警告。

    【讨论】:

    • 我从 wait(&status) shell.c 收到以下错误:在函数âint main()â:shell.c:100:错误:没有匹配的函数调用 âwait::wait(int *)â /usr/include/bits/waitstatus.h:68: 注意:候选者是:wait::wait() /usr/include/bits/waitstatus.h:68: 注意:wait::wait(const wait&)
    • 好吧,(a) 你应该使用 C 编译器而不是 C++ 编译器进行编译(或者你应该重新标记你的问题)和 (b) 你应该使用#include &lt;sys/wait.h&gt;(参见wait() and waitpid() )。 -W*-prototypes 选项的优点之一是,当您在调用函数之前没有函数范围内的原型时会收到警告。
    • 我的错误是使用了错误的编译器。这是习惯。但是使用#include 很好。修复了一切。我假设它已经存在并且没有检查。现在一切正常。大有帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多