子在fork中没有正确终止

时间:2011-04-17 04:23:28

标签: c++ exec fork strcpy

我正在为一个小shell编写一个c程序。用户输入命令,代码使用exec()函数执行它。

我需要在这个过程中有一个fork,所以所有工作都在子进程中完成。唯一的问题是子进程无法正常终止并执行命令。当我在没有fork的情况下运行代码时,它会完美地执行命令。

问题似乎来自我创建要在execv调用中使用的字符串的位置。这是我调用strcpy的代码行。如果我发表评论,事情就好了。我也尝试将其更改为strncat同样的问题。我对于造成这种情况的原因一无所知,欢迎任何帮助。

#include <sys/wait.h>
#include <vector>
#include <sstream>
#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <unistd.h>

using namespace std;

string *tokenize(string line);
void setCommand(string *ary);

string command;
static int argument_length;

int main() {
    string argument;
    cout << "Please enter a unix command:\n";
    getline(cin, argument);
    string *ary = tokenize(argument);

    //begin fork process
    pid_t pID = fork();
    if (pID == 0) { // child
        setCommand(ary);

        char *full_command[argument_length];
        for (int i = 0; i <= argument_length; i++) {
            if (i == 0) {
                full_command[i] = (char *) command.c_str();
                //  cout<<"full_command " <<i << " = "<<full_command[i]<<endl;
            } else if (i == argument_length) {
                full_command[i] = (char *) 0;
            } else {
                full_command[i] = (char *) ary[i].c_str();
            //  cout<<"full_command " <<i << " = "<<full_command[i]<<endl;
            }
        }    

        char* arg1;
        const char *tmpStr=command.c_str();        
        strcpy(arg1, tmpStr);
        execv((const char*) arg1, full_command);
        cout<<"I'm the child"<<endl;
    } else if (pID < 0) { //error
        cout<<"Could not fork"<<endl;
    } else { //Parent
        int childExitStatus;
        pid_t wpID = waitpid(pID, &childExitStatus, WCONTINUED);
        cout<<"wPID = "<< wpID<<endl;
        if(WIFEXITED(childExitStatus))
            cout<<"Completed "<<ary[0]<<endl;
        else
            cout<<"Could not terminate child properly."<<WEXITSTATUS(childExitStatus)<<endl;
    }

    // cout<<"Command = "<<command<<endl;
    return 0;
}

string *tokenize(string line) //splits lines of text into seperate words
{
    int counter = 0;
    string tmp = "";
    istringstream first_ss(line, istringstream::in);
    istringstream second_ss(line, istringstream::in);

    while (first_ss >> tmp) {
        counter++;
    }

    argument_length = counter;
    string *ary = new string[counter];
    int i = 0;
    while (second_ss >> tmp) {
        ary[i] = tmp;
        i++;
    }

    return ary;
}

void setCommand(string *ary) {
    command = "/bin/" + ary[0];

// codeblock paste stops here

1 个答案:

答案 0 :(得分:2)

你说:

  

我调用的代码行   的strcpy。

您尚未分配任何内存来存储字符串。 strcpy的第一个参数是目标指针,并且您正在为该指针使用未初始化的值。从strcpy手册页:

  

char * strcpy(char * s1,const char * s2);

     

stpcpy()和strcpy()函数将字符串s2复制到s1(包括   终止'\ 0'字符)。

可能还有其他问题,但这是我接受的第一件事。