我正在编写一个程序,它接收命令名称和参数以及可选的字符串“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 参数未通过时有效,但在通过时我尝试用“&”替换它,但它没有用,感谢各位的帮助。