我有一个客户端服务器程序,其中服务器是一个简单的 shell
命令运行良好,参数传递正常,但我认为 execve 卡住
所以这是简单的 shell 代码 -- 前半部分用于验证该命令是否在此 shell 中被允许
while((n = Rio_readlineb(&rio, buf, MAXLINE)) != 0){ //loop until connection has been terminated
if (!strcmp(buf, "quit\n")){
printf("User %s disconnected.\n", username);
flag1 = 0; //the user will need to login again
}
if (flag1 == 1){ //the user is loged in
bg = p3parseline(buf, argv_for_shell);
strtok(buf, "\n");
printf("User %s sent the command '%s' to be executed.\n", username, buf);
// temp = argv_for_shell[0];
// strcat(temp, "\n");
//check if the command is allowed
flag2 = 0; //set command allowed? flag back to false
file = Fopen("rrshcommands.txt", "r");
while (Fgets(command, MAXLINE, file) != NULL){
strtok(command, "\n");
if (!strcmp(argv_for_shell[0], command)){
flag2 = 1;
}
}
Fclose(file);
if (flag2 == 0){ //case where the command is not allowed
printf("The command '%s' is not allowed.\n", buf);
strcpy(buf, "Command not allowed\n");
Rio_writen(connfd, buf, strlen(buf));
}
else{
if ((pid = fork()) == 0) { /* Child runs user job */
printf("Fork/Execing the command %s on behalf of the user.\n", argv_for_shell[0]);
Dup2(connfd, 1);
if (execve(argv_for_shell[0], argv_for_shell, environ) < 0) {
printf("%s: Command not found.\n", argv_for_shell[0]);
exit(0);
}
printf("Finished execing\n");
}
/* Parent waits for foreground job to terminate */
if (!bg) {
int status;
if (waitpid(pid, &status, 0) < 0)
unix_error("waitfg: waitpid error");
memset(&buf[0], 0, sizeof(buf)); //flush the buffer
Rio_writen(connfd, buf, strlen(buf));
}
else{
memset(&buf[0], 0, sizeof(buf)); //flush the buffer
Rio_writen(connfd, buf, strlen(buf));
}
signal(SIGCHLD, reap_background);
}
}
我之前发布了一个与此相关的问题,但是由一个单独的问题引起的——也请随意阅读那个问题
我在 execve 下添加了一个 printf 语句来确认程序是否到达那个点,但它没有
shell 的输出看起来像
User k logging in from 127.0.0.1 at TCP port 1024.
User k successfully logged in.
User k sent the command '/bin/sleep 1&' to be executed.
Fork/Execing the command /bin/sleep on behalf of the user.
有什么想法吗?
最佳答案
据我所知,这是意料之中的事情。首先你 fork()
,然后你打印“Fork/Execing the command/bin/sleep behalf of the user.”,然后你调用 execve()
。对 execve()
的调用永远不会返回(假设它成功),因为 execve()
替换了当前程序。
因此这一行:
printf("Finished execing\n");
永远无法到达。
这正是您(大概)首先执行 fork()
的原因。您应该做的是 wait()
等待 fork()
的进程完成。
还有,这条线是做什么用的?
signal(SIGCHLD, reap_background);
关于c - execve '/bin/sleep'命令卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34120256/