Implement the '&&' function in a shell


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers Implement the '&&' function in a shell
# 1  
Old 01-11-2014
Implement the '&&' function in a shell

Hello, I'm currently implementing the && function in a shell using C. For example, if we input cmd1 && cmd2, then cmd2 executes only when cmd1 exits successfully. I'm thinking about:

Code:
int main() {
  int i;
  char **args; 

  while(1) {
    printf("yongfeng's shell:~$ ");
    args = get_line();
    if (strcmp(args[0], "exit") == 0) exit(0);     /* if it's built-in command exit, exit the shell */
    if('&&') parse_out_two_commands: cmd1, cmd2;
    if (execute(cmd1) != -1)   /* if cmd1 successfully executed */
      execute(cmd2);       /* then execute the second cmd */
  }
}

int execute(char **args){
  int pid;
  int status;   /* location to store the termination status of the terminated process */
  char **cmd;   /* pure command without special charactors */

  if(pid=fork() < 0){   //fork a child process, if pid<0, fork fails
    perror("Error: forking failed");
    return -1;
 }

 /* child */
 else if(pid==0){             /* child process, in which command is going to be executed */
   cmd = parse_out(args);
   /* codes handleing I/O redirection */

   if(execvp(*cmd, cmd) < 0){   /* execute command */
     perror("execution error");
     return -1;
   }
  return 0;
 }

 /* parent */
 else{         /* parent process is going to wait for child or not, depends on whether there's '&' at the end of the command */
  if(strcmp(args[sizeof(args)],'&') == 0){
     /*  handle signals */
  }
   else if (pid = waitpid(pid, &status, 0) == -1) perror("wait error");
  }
}

So I'm using another function int execute(char ** args) to do the actual work. Its return type is int because I wan to know whether the command exits successfully. But I'm not sure here whether the parent process can get the return value from the child since they're two different processes.

Or should I decide whether to execute the second command in the child process, by forking another process to run it? Thanks a lot.
# 2  
Old 01-11-2014
Is this another homework assignment?
# 3  
Old 01-12-2014
no it's not. I'm just self-studying.
# 4  
Old 01-13-2014
Quote:
Originally Posted by Yongfeng
Hello, I'm currently implementing the && function in a shell using C. For example, if we input cmd1 && cmd2, then cmd2 executes only when cmd1 exits successfully. I'm thinking about:

Code:
int main() {
  int i;
  char **args; 

  while(1) {
    printf("yongfeng's shell:~$ ");
    args = get_line();
    if (strcmp(args[0], "exit") == 0) exit(0);     /* if it's built-in command exit, exit the shell */
    if('&&') parse_out_two_commands: cmd1, cmd2;
    if (execute(cmd1) != -1)   /* if cmd1 successfully executed */
      execute(cmd2);       /* then execute the second cmd */
  }
}

int execute(char **args){
  int pid;
  int status;   /* location to store the termination status of the terminated process */
  char **cmd;   /* pure command without special charactors */

  if(pid=fork() < 0){   //fork a child process, if pid<0, fork fails
    perror("Error: forking failed");
    return -1;
 }

 /* child */
 else if(pid==0){             /* child process, in which command is going to be executed */
   cmd = parse_out(args);
   /* codes handleing I/O redirection */

   if(execvp(*cmd, cmd) < 0){   /* execute command */
     perror("execution error");
     return -1;
   }
  return 0;
 }

 /* parent */
 else{         /* parent process is going to wait for child or not, depends on whether there's '&' at the end of the command */
  if(strcmp(args[sizeof(args)],'&') == 0){
     /*  handle signals */
  }
   else if (pid = waitpid(pid, &status, 0) == -1) perror("wait error");
  }
}

So I'm using another function int execute(char ** args) to do the actual work. Its return type is int because I wan to know whether the command exits successfully. But I'm not sure here whether the parent process can get the return value from the child since they're two different processes.

Or should I decide whether to execute the second command in the child process, by forking another process to run it? Thanks a lot.
If this isn't homework, please tell us what book you're using as a study guide.

This is a very strange mix of pseudo-code and real code. I can't tell by reading it which parts you think are complete and which parts are placeholders for future work. It is, however, clear that this code will not compile.

The first thing you need to do is be sure you #include all of the headers needed for the standard functions you're using.

Then, concerning your question about getting the exit status of a child:
The code:
Code:
   if(execvp(*cmd, cmd) < 0){   /* execute command */
     perror("execution error");
     return -1;
   }
  return 0;

is strange. Please look at the execvp() (or exec) man page again. There is no return from a successful call to execvp().

Then look at the waitpid() man page. You should see that waitpid(), as you are using it, saves the exit status of the child into the variable status. The way you have your code written:
Code:
   else if (pid = waitpid(pid, &status, 0) == -1) perror("wait error");

does not set a return value for your execute() function if waitpid() succeeds. You probably want to change the line above to something more like:
Code:
   else if (pid = waitpid(pid, &status, 0) == -1) perror("wait error");
   else return(status);

and change:
Code:
    if (execute(cmd1) != -1)   /* if cmd1 successfully executed */

to something like:
Code:
    if (execute(cmd1) == 0)   /* if cmd1 successfully executed */

# 5  
Old 01-14-2014
Hello Don, thanks so much for your reply. I'm using Advanced Programming in the Unix Environment and Modern Operating Systems as my reference.

As for the question, I just want the parent to get the command execution result(successful or not) from the child, because I want to do &&(conditional execution). If execvp successfully executes in the child, how does the parent know it because it does not return any value. Thanks.
# 6  
Old 01-14-2014
The first and second command in an && chain aren't parent/child as much as siblings. The parent controlling them gets the value, and can tell whether to launch the next one.
This User Gave Thanks to Corona688 For This Post:
 
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Homework & Coursework Questions

How to Dynamically Pass Parameter to plsql Function & Capture its Output Value in a Shell Variable?

Use and complete the template provided. The entire template must be completed. If you don't, your post may be deleted! 1. The problem statement, all variables and given/known data: 2. Relevant commands, code, scripts, algorithms: #! /bin/ksh v="ORG_ID" ... (2 Replies)
Discussion started by: sujitdas2104
2 Replies

2. Shell Programming and Scripting

SFTP Shell Script Get & Delete && Upload & Delete

Hi All, Do you have any sample script, - auto get file from SFTP remote server and delete file in remove server after downloaded. - only download specify filename - auto upload file from local to SFTP remote server and delete local folder file after uploaded - only upload specify filename ... (3 Replies)
Discussion started by: weesiong
3 Replies

3. UNIX for Dummies Questions & Answers

MAN and read & write function

How to use MAN to find information about read() and write() function ? The command "man read" show some rubbish, for example "man open" show great information about function I need. (2 Replies)
Discussion started by: bbqtoss
2 Replies

4. Shell Programming and Scripting

Replace & sign to &amp word

Hi, I have text file abc.txt. In this file, I have the following data. Input: Mr Smith &amp Mrs Smith Mr Smith &apos Mrs Smith Mr Smith & Mrs Smith Mr Smith& Mrs Smith Mr Smith &Mrs Smith Output: Mr Smith &amp Mrs Smith Mr Smith &apos Mrs Smith Mr Smith &amp Mrs Smith Mr Smith&amp... (4 Replies)
Discussion started by: naveed
4 Replies

5. Shell Programming and Scripting

replace & with &amp; xml file

Hello All I have a xml file with many sets of records like this <mytag>mydata</mytag> <tag2>data&</tag2> also same file can be like this <mytag>mydata</mytag> <tag2>data&</tag2> <tag3>data2&amp;data3</tag3> Now i can grep & and replace with &amp; for whole file but it will replace all... (4 Replies)
Discussion started by: lokaish23
4 Replies

6. Shell Programming and Scripting

PHP read large string & split in multidimensional arrays & assign fieldnames & write into MYSQL

Hi, I hope the title does not scare people to look into this thread but it describes roughly what I'm trying to do. I need a solution in PHP. I'm a programming beginner, so it might be that the approach to solve this, might be easier to solve with an other approach of someone else, so if you... (0 Replies)
Discussion started by: lowmaster
0 Replies

7. Shell Programming and Scripting

Shell Script to display function names (called & defined) in a C++ Source Code

Hello to all, I am looking for a way to display only the names of function (calls & definition) of a C++ source code.There is already a post related to this, but the script is to find the functions using a specific variable, and the replies are not that convincing since they cannot be used for... (2 Replies)
Discussion started by: frozensmilz
2 Replies

8. UNIX for Advanced & Expert Users

Network Shell Script & Blade Logic & Network Security

I am going to take up a position in Data & Network Security. I would need to write network shell scripts doing the following task: Going to around 2000 servers and findout which groups has access to each servers and which ids are there in each group that has access. I need to implement... (1 Reply)
Discussion started by: pinnacle
1 Replies

9. Shell Programming and Scripting

Array split function & hashes

Hi, If this is the array that is being returned to me: How would I get the values for each of the 3 records? This works for 1 Record: foreach $item (@results) { ($id, $id2, $name, $date, $email) = split(/\|/, $item, 5); print "$name<br>"; } (2 Replies)
Discussion started by: novera
2 Replies

10. UNIX for Dummies Questions & Answers

subshell & background function

Hello all, Can someone explain to me the advantage between using subshell over a function call in scripts? To me these are the same. Am I wrong to think this? (4 Replies)
Discussion started by: larry
4 Replies
Login or Register to Ask a Question