Mus*_*pha 1 linux posix system system-calls execvp
我正在编写一个程序,该程序接收命令名称和参数,并且可选地在末尾接收字符串“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);
}
Run Code Online (Sandbox Code Playgroud)
输入示例:
./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
Run Code Online (Sandbox Code Playgroud)
当 bg 参数未传递时,我的代码可以工作,但是当传递时,我尝试用“&”替换它,但它不起作用,感谢大家的帮助。
使程序后台运行与否的区别在于等待它完成还是不等待。所以你实际上不必使用两个不同的 execvp。但是,您需要从参数中删除尾随的 bg。附加 & 不会执行任何操作 - & 是 shell 的元字符,它告诉 shell 不要等待正在执行的程序。
所以,你应该做的是:
if the last argument is "bg" : decrease argc by one, set the argument that had the bg to null
fork and execvp what's in argv
if the last argument was "bg", do NOT call wait(); else call wait.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16345 次 |
| 最近记录: |