如何跟踪未被等待的子进程的终止/运行"对于?

时间:2017-10-24 06:33:00

标签: c++ linux shell process

我有一个作业,我必须在C ++中编写一个子shell。本质上,我正在分叉(如果输入不是作业或退出),并且在子进程中,我正在调用exec来运行命令。它需要与父进程一起运行,例如,如果我调用sleep 100,程序应该立即准备好运行下一个命令,因为父进程不是等待"因为我使用的是WNOHANG。但是,我的问题是当我需要跟踪实际状态时 - 如果睡眠仍在运行,我希望能够得到该命令仍在运行,但我无法这样做。当我使用各种宏时,它总是显示为已退出。我不知道如何以不同的方式处理这个问题,并希望得到一些指导。  (我没有包含变量的声明,因为这个网站的编辑因某种原因弄乱了它)

    do{

        cout << "# ";
        getline(cin, input);

        if (input == "jobs")
        {
            cout << "Process ID | State        | Command " << endl;
            cout << "-----------+--------------+-----------------------------------------------" << endl;

            //jobs stuff goes here, need to print pids, states, and commands

            if(counter == 0)
            {
                cout << " [NO PROCESSES] " << endl;
            }
            else
            {
                for(i = 0; i < counter; i++)
                {
                    cout << pidArray[i] << " ";
                    cout << statusArray[i] << " ";
                    cout << cmdArray[i] << endl;
                }
            }
        }
        else
        {
            cmdArray[i] = input;
            i++;
            counter++;
            pid = fork();

            if( pid == 0)
            {
                execl("/bin/sh", "sh", "-c", input.c_str(), (char *)0);
                //break;
            }
            else if (pid == -1)
            {
                break;
            }
            else
            {
                pidArray[i-1] = pid;
                //int rc = waitid(P_PID, pid, NULL, WNOHANG);
                // int rc =waitpid(pid, &status, WNOHANG | WNOWAIT );
                //exitChecker = waitpid(pid, &status, WNOHANG);

                usleep(100000);

                if (WIFEXITED(status))
                {
                    cout << "terminated" << endl;
                }
                else
                {
                    cout << "running" << endl;
                }
            }
        }
    }while(input != "exit");
    return 0;
}

提前致谢。

0 个答案:

没有答案