0

我开发的这段代码只是为了解决我正在开发的另一个大型程序中遇到的问题。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <cstring> 
#include <cstdlib> 
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <limits.h>
#include <string>
#include <iostream>

using namespace std;
void processLine (char []);
void readLine(char []);

const int LIMIT = 512;
int main(int argc, char *argv[])
{
    char oneLine[LINE_MAX];
    readLine(oneLine);
    
        
    return 0;
}
void readLine(char line[])
{
    processLine(line);
    printf("Annoying line\n");
}
void processLine(char line[])
{
    
    pid_t process;
    int child_status;

    string input;
    cout << "Input: ";
    cin >> input;

    
        process = fork();
        if(process == 0)
        { // do nothing
        }
        else 
        {
                        //parent
                    if(input == "quit")
            {
                printf("Quit command found ! \nExiting ");
                    
                for(int i = 0;i < 3;i++)
                {
                    printf(".");
                    fflush(stdout);
                    sleep(1);
                    
                }
            
                printf("\n");
                    exit(0);            
            }
            else
            {
                wait(&child_status);
            }
        }
    
}

我的目标很简单,当用户输入退出时。

我只会显示

找到退出命令

退出...

这三个点中的每一个之间都有一秒钟的延迟。

但是我得到的输出是

找到退出命令

退出。烦人的线。。

我想知道这条恼人的线怎么会在第一个点之后打印,即使它来自调用函数,而且轮到它打印到终端了????

有任何想法吗。我花了 10 个小时试图解决这个问题

4

1 回答 1

1

在子进程中你的// do nothing落入并返回main()打印线。 fork()制作两个继续执行的副本。通常孩子会exec()立即打电话来运行其他东西(永远不会返回),但你没有做那样的事情。

于 2016-02-07T07:07:56.880 回答