#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
char *getdir() /*find working directory*/
{
char *buffer;/*buffer is going to be used in getcwd function to get the current directory*/
char *path_buffer;//path_buffer is going to contain the directory//
long maxsize = pathconf(".", _PC_PATH_MAX);/* we set maxsize as the maximum pathname length*/
if((buffer=(char*) malloc((size_t)maxsize))!=NULL)
{
path_buffer=getcwd(buffer,maxsize); /*get the current directory*/
printf("\nMy working directory = %s",path_buffer);
return path_buffer;
}
else{
exit(-1);
}
}
char * getcmline() /*get command from stdin by the user*/
{
int bytes_read;
int nchars=200;/*max possible number for the input of the user*/
int nbytes=(sizeof(char))*nchars; /*size of chars in bytes*/
char *line=(char*) malloc(nbytes+1);
bytes_read=getline(line,&nbytes,stdin);/*read line from stdin*/
if(bytes_read == -1){
printf("Read line error");
exit(-1);
} /*error handling for bytes_read*/
else{
if(line[strlen(line)-1]=='\n')
{
line[strlen(line)-1]='\0'; /*change new line character in the end of the line of stdin*/
}
}
return line;
}
int main(void)
{
pid_t pid,child_pid;
int rv=0;
char* exit_string="exit";
char *path_buffer=NULL;
int nchars=200;
int nbytes=(sizeof(char))*nchars;
char *line=malloc(nbytes+1);
char *commands[2];
while(1){
switch(pid = fork())
{
case -1:
perror("fork"); /* something went wrong */
exit(1);
case 0:
printf(" CHILD: This is the child process!\n");
child_pid=getpid();
printf(" CHILD: My PID is %d\n", child_pid);
path_buffer=getdir();/*get the directory path*/
line=getcmline();/*get a command by the user*/
if(strcmp(line,exit_string)==0)
{
rv=3;
exit(rv);
}
commands[0]=line;
commands[1]=NULL;
execvp(commands[0],commands);
perror("Execution error");
exit(-1);
default:
waitpid(-1, &rv, 0);
if(WIFEXITED(rv)){
printf("Child exited normally and child's exit status is: %d\n", WEXITSTATUS(rv));
if((WEXITSTATUS(rv))==3){
exit(1);
}
}
}
}
return 0;
}
我在 中进行了更改getline
,rv
并为execvp
. 但是现在发生的错误是在我输入例如“ls”之后。它说:
执行错误:没有这样的文件或目录。
再次感谢您的帮助和我缺乏知识。
错误似乎在行变量中,但我无法理解问题所在!
这里给出了解决方案。它应该是 line[(strlen)-1] 而不是 line[(strlen-1)]