【发布时间】:2014-01-14 11:01:49
【问题描述】:
我正在编写一个程序,它接收命令名称和参数以及可选的字符串“bg”,如果传递了“bg”字符串,我的程序应该在后台执行命令及其参数,如果不是在前台,这是我的代码:
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdio.h>
#include<errno.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
pid_t pid;
int state;
if( (pid=fork())<0) {
perror("\nError in fork");
exit(-1);
}
else if(pid==0) {
if(strcmp(argv[argc-1], "bg") == 0 ){
strcpy(argv[argc-1],"&");
if( (execvp(argv[1], argv)<0)) {
perror("\nError in first execvp");
exit(-1);
}
}
else{
if( (execvp(argv[1], argv+1)<0)) {
perror("\nError en second el execvp");
exit(-1);
}
}
}
wait(&state);
printf("\nMy child %d terminated with state %d\n",pid,state);
exit(0);
}
输入示例:
./myprogram ls -lai bg // in this case my program should execute "ls -lai" in background
./myprogram ls -lai // in this case it should execute command normally in foreground
我的代码在 bg 参数未通过时有效,但在通过时我尝试用“&”替换它,但它不起作用,感谢各位帮助。
【问题讨论】:
-
你明白“在后台运行程序”是什么意思吗?
-
&不是由execvp()处理的,而是由shell 处理的,类似于处理bg令牌的方式。由于你没有使用 shell 来运行命令,所以它不会有任何效果。 -
如果你想在后台运行,直接退出,不要调用
wait()。 -
@Ignacio Vazquez-Abrams 是的,我想是的,这是一个家庭作业。
标签: linux system posix system-calls execvp