使用的strtok(),并在后台执行UNIX命令 [英] Use strtok() and execute UNIX command in background
问题描述
我试图写它创建一个UNIX外壳的C程序。 (;指定,当与放大器背景)在当UNIX命令键入这个壳,外壳应在前台或后台执行。我得到在前台运行的命令,但我不能在后台运行。
这里是我的code:
I'm trying to write a C program which creates a UNIX shell. In this shell when a UNIX command is typed, the shell should execute it in the foreground or background (background when & is specified). I'm getting the command to run in the foreground but I can't run it in the background. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#define MAX_LENGTH 1024
#define DELIMS " \t\r\n"
int main(int argc, char *argv[])
{
char *cmd, *bg;
char line[MAX_LENGTH];
pid_t fpid,bpid;
int status;
while (1)
{
fpid=10;
bpid=10;
printf("myshell > ");
if (!fgets(line, MAX_LENGTH, stdin))
break;
int j=0;
if(cmd = strtok(line, DELIMS))
{
bg = strtok(line," ");
while(bg!=NULL)
{
printf("%s",bg);
bg = strtok(NULL, " ");
if(strcmp(bg, "&") == 0)
break;
}
printf("%s", bg);
if(strcmp(cmd,"exit")==0)
break;
else if(strcmp(bg,"&")==0)
{
bpid=fork();
//waitpid(bpid,&status,0);
system(line);
exit(0);
}
else
{
//fpid=fork();
//if(fpid==0)
//{
system(line);
// exit(0);
//}
//else
//{
// waitpid(fpid,&status,0);
//}
}
}
}
return(0);
}
有人可以帮我这个项目?我真的需要这为我的家庭作业。
Can someone please help me in this program? I really need this for my homework.
推荐答案
阅读手册页叉()
。返回0 code意味着你的孩子,非零(非负),意味着你的父。您应该基于具有不同的逻辑,并使用系统()
(或子分支更好的exec *()
Read the manpage for fork()
. The return code of 0 means that you are in the child, non-zero (non-negative) means you are the parent. You should have different logic based on that and use system()
(or better exec*()
in the child branch.
下面是你应该有典型的逻辑是:
Here's the typical logic you should have:
tokenize(line)
if (last token is '&') {
rc = fork();
if (rc < 0)
handle error;
else if (rc > 0) { /* in parent, rc = child pid */
do whatever you planned to do in the parent process
}
else { /* in child */
use exec*() to start the child command
}
}
else { /* foreground execution */
use system() to run command
}
这篇关于使用的strtok(),并在后台执行UNIX命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!