孩子没有正确地终止叉
问题描述:
我正在写一个小程序的类的c程序。用户输入一个命令,代码使用exec()
函数执行它。孩子没有正确地终止叉
我需要在这个过程中有一个分叉,所以所有的工作都是在子进程中完成的。唯一的问题是孩子不会正确终止并执行命令。当我运行没有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
答
你说:
它的代码行,我叫 的strcpy。
您尚未分配任何内存来存储您的字符串。 strcpy的第一个参数是目标指针,并且您正在为该指针使用未初始化的值。从strcpy手册页:
char * strcpy(char * s1,const char * s2);
stpcpy()和strcpy()函数将字符串s2复制到s1(包括终止'\ 0'字符的 )。
可能还有其他问题,但这是我第一次选择。
+0
我真的很讨厌自己,因为这是一个多么简单的修复,但这似乎是一个确切的问题。我将arg1的定义更改为char arg1 [command.length()],现在它完美运行。万分感谢! – gdawgrancid 2011-04-17 04:47:44
我清理了你的代码,仍然无法理解你正在尝试做什么。我猜你也不太了解它。从你的老师那里寻求帮助。 – msw 2011-04-17 04:38:56