谁能告诉我为什么我的shmat不能正常工作呢?我不确定为什么int fam没有正确存储数据并返回0 在我尝试在子进程中递增它之后。我需要使用存储的内存,以便我可以更新我的其他类。任何人都可以帮我弄清楚发生了什么事吗?感谢
void Execute::terminal(const vector<Command*>& tokens) //runs all the commands
{
key_t key;
int shmid;
// int* fam = (int*)shmat(shm_id, NULL, 0);
//key = ftok("/home/beej/somefile3", 'R');
//shmid = shmget(key, 1024, 0644 | IPC_CREAT);
shmid = shmget(key, 10*sizeof(int), 0644 | IPC_CREAT);
// fam = static_cast<int*>(shmat(shmid, (void *) 0, 0));
int *fam = /*static_cast<int*>*/(int*)(shmat(shmid, NULL, 0));
fam = 0;
cout << fam << endl;
int termstat;
bool temp;
vector<char*>convert;
vector<string> parse;
string text;
// ; = next command is always executed
// && = next command only executes if previous command succesfully executed
// || = next command only executes if previous command didnt
// # = comment
cout << "terminal is working - " << tokens.size() << endl;
for(int x = 0; x < tokens.size(); x++)
{
convert.resize(0);
text = tokens.at(x)->tokenCheck();
parsecmd(text,parse);
for(int i = 0; i < parse.size(); i++)
{
convert.push_back(to_char(parse[i]));
}
char** arg = &convert.at(0);
pid_t parent = getpid();
pid_t pid = fork();
if(pid < 0)
{
perror("Error: fork failed");
_exit(-127);
}
if(pid > 0)
{
waitpid(pid, &termstat, 0);
}
else
{
if(tokens.at(index)->signCheck() == 0) //comment - delete this token
{
tokens.at(index)->addstatus(true);
}
if(tokens.at(index)->signCheck() == 1) // ; always runs
{
tokens.at(index)->addstatus(true);
int check = execvp(arg[0],arg);
if(check < 0)
{
cout << fam << endl;
fam ++;
shmdt(fam);
cout << fam << endl;
cout << "Error: " << arg[0] <<" command not found (;)" << endl;
tokens.at(index)->addstatus(false);
_exit(-127);
}
else
{
tokens.at(index)->addstatus(true);
_exit(5);
}
}
if(tokens.at(index)->signCheck() == 2) // || runs only if first fails
{
if(tokens.at(index-1)->statusCheck() == false)
{
int check = execvp(arg[0],arg);
if(check < 0)
{
fam ++;
cout << "Error: " << arg[0] <<" command not found (||)" << endl;
tokens.at(index)->addstatus(false);
_exit(-127);
}
else
{
tokens.at(index)->addstatus(true);
_exit(5);
}
}
}
if(tokens.at(index)->signCheck() == 3) // && runs only if first passes
{
if(tokens.at(index-1)->statusCheck() == true)
{
int check = execvp(arg[0],arg);
if(check < 0)
{
fam ++;
cout << "Error: " << arg[0] <<" command not found (&&)" << endl;
tokens.at(index)->addstatus(false);
_exit(-127);
}
else
{
tokens.at(index)->addstatus(true);
_exit(5);
}
}
}
}
cout << "fam at end: " <<fam << endl;
if(fam == 0)
{
tokens.at(index)->addstatus(true);
}
this->index++; // keeps track of which command is being executed
cout << "index: " << index << endl;
}
for(int i = 0; i < tokens.size(); i++){
cout << tokens[i]->statusCheck() << endl;
}