background process


 
Thread Tools Search this Thread
Top Forums Programming background process
# 1  
Old 05-30-2003
background process

I have made a shell that accept a command and parameters. It is working properly. I have tryed to implement background process in main(). But i dont know to implement them. Can anyone give me a lille example??

Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/* The following define's belongs to read_command(..) */
#define MAXPARMS	20
#define MAXPARMLEN	255
#define MAXINPUT	255
#define shell		"cesh"

/* The Command line parser */

/*------------------------------------------------------------------*/
/* read_command:                                                    */
/*   Print the prompt and get one characters from the users which   */
/*   makes up an entire command line entry                          */
/*------------------------------------------------------------------*/

void read_command(char * command, char * parameters[])
{
  char input[MAXINPUT];
  char * parm;
  char c;
  int i;

  /* initialize the whole parameters array to NULL pointers */
  for (i=0;i<MAXPARMS;i++)
    {
      parameters[i]=NULL;
    }

  i=0;
  input[0]='\0';

  /* loop until some characters are entered on the command line */
  do
    {
      printf("%s> ", shell);
      c=getchar();
      while ((c != '\n') && (i < MAXINPUT-1))
        {
          input[i]=c;
          i++;
          c=getchar();
        }
      input[i]='\0';
    } while (strlen(input)==0);

  /* copy the first "word" on the command line into the command var */
  /* this also initializes the use of the strtok function */
  strcpy(command, strtok(input, " "));
  parameters[0]=malloc((MAXPARMLEN+1)*sizeof(char));
  strcpy(parameters[0], command);
  i=1;

  /* separate all of the "words" on the command line. Each becomes */
  /* a string pointed to by the parameters array using strtok. */
  do
    {
      if (parm=strtok(NULL, " "))
        {
          parameters[i]=malloc((MAXPARMLEN+1)*sizeof(char));
          strcpy(parameters[i],parm);
        }
      else
        {
          parameters[i]=NULL;
        }
      i++;
    } while((parameters[i-1]!=NULL) && (i < MAXPARMS));

  return;
}

int main(void)
{
char name[10];
char *argv[MAXPARMS];

read_command(name, argv);

/*background process*/
int pid, status;
int BGRND = 0;

do 
{
	if (strcmp(argv[0], "&")==0))
	{
		BGRND = 1;
	}
	if ( (pid = fork() < 0 )
			return 0;

	if(pid == 0 )
	{
		if ((execvp(argv[0], argv)) == -1)
			printf("%s: Command not found.\n", tokenstr);
			return 0;
	}
	if(BGRND == 0)
	{
		while (waitpid(-1, &status, 0) != pid);
	}
	BGRND = 0;
}while(strcmp(name,"exit));

return 0;
}

# 2  
Old 05-30-2003
Do you mean just running something in the background? You do that by placing an ampersand (&) after the command. Like if I wanted to run the date command in the background (which would be silly, but whatever), I'd type date & at the prompt.

Click here for a more detailed explanation.
# 3  
Old 05-30-2003
Oombera ... Yes that what i want to do but i want to make my own code. I am trying to learn simple shell programming. I have made a new code to replace the first version i post in here. Iam not sure about that background process should be implement like this??+

<code>

int main(void)
{
char name[10];
char *argv[MAXPARMS];
int i;
int PID, status;
int BGRND = 0;

read_command(name, argv);


/*background process*/

if ((strcmp(name, "back")==0) & (strcmp(argv[1], "&")==0))

{
BGRND = 1;

if ( (PID = fork()) < 0 )
return 0;

if(PID == 0 )
{
if ((execvp(argv[1], argv)) == -1)
perror("Fejl");
//printf("%s: Command not found.\n", tokenstr);
return 0;
}
if(BGRND == 0)
{
while (waitpid(-1, &status, 0) != PID);
}
BGRND = 0;

}

return 0;
}</code>
# 4  
Old 05-30-2003
Re: background process

I see a lot of errors in your code. I do not believe that it works. In fact when I look at code like this...
Quote:
Originally posted by badshah

if (strcmp(argv[0], "&")==0))
if ( (pid = fork() < 0 )
}while(strcmp(name,"exit));
I don't even believe that it will compile at all.

In general terms, you are on the right track. If we assume a shell without job control, "background" just means that we do not wait for the child.

A few comments...look at your line
if ( (pid = fork() < 0 )
The parentheses do not match up. It is critical that the test is done right. It should be
if ( (pid = fork()) < 0 )

When a system call fails, it will return a -1. I prefer explicitly testing for that. This is how you handled the execvp() system call. Also when a system call fails, it sets errno to an error code. If you display this value, it can help in debugging. And there is a sys_errlist that can decode errno. I like to do that as well. Also errors should go to stderr, not stdout. And exit codes should indicate whether or not the program worked. Put all of that together and this is how I would do it...
Code:
if ( (pid=fork()) == -1 ) {
         fprintf(stderr, "fork failed \n");
         fprintf(stderr, "errno = %d \n", errno);
         fprintf(stderr, "%s\n", sys_errlist[errno]);
         exit(1);
}

Now to use errno and sys_errlist. you are supposed to include errno.h. But sometimes another include picks them up.

There is no need to waitpid in a loop. Just wait for the process once.

And it looks like you are reading a command once, and then looping on it forever. You need to read a new command inside your loop.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Make background process interact with fg process

Hi, I have written a menu driven shell script in which as per the choice, I run the another script on background. For eg: 1. get info 2)process info 3)modify info All the operations have different scripts which i schedule in background using &. However I wish to display the error... (0 Replies)
Discussion started by: ashima jain
0 Replies

2. Shell Programming and Scripting

How to put FTP process as a background process/job in perl?

Hi, I am using net::ftp for transferring files now i am trying in the same Linux server as a result ftp is very fast but if the server is other location (remote) then the file transferred will be time consuming. So i want try putting FTP part as a background process. I am unaware how to do... (5 Replies)
Discussion started by: vanitham
5 Replies

3. AIX

Background process

how to check the process running in background? how can i run a process in background? pls explain with commands (1 Reply)
Discussion started by: udtyuvaraj
1 Replies

4. UNIX for Dummies Questions & Answers

Script to start background process and then kill process

What I need to learn is how to use a script that launches background processes, and then kills those processes as needed. The script successfully launches the script. But how do I check to see if the job exists before I kill it? I know my problem is mostly failure to understand parameter... (4 Replies)
Discussion started by: holocene
4 Replies

5. UNIX for Dummies Questions & Answers

Background Process

I need to submit a script that will continue to run after logging out and after a reboot or shutdown. I entered the following: nohup script & The script continues to run in the background after logging off the system but is killed after a reboot or shutdown. Any help would be greatly... (1 Reply)
Discussion started by: powwm
1 Replies

6. Shell Programming and Scripting

Help in background process

Hi, I have a main script(main.ksh) within which I have called another script(sub.ksh). The sub.ksh script is made to run in the background using '&'. The main.ksh script logs the information in a logfile main_ddmmyy and the sub.ksh script also logs the information in the log file sub_ddmmyy.... (5 Replies)
Discussion started by: chella
5 Replies

7. UNIX for Dummies Questions & Answers

background process

How, can I hide background process's output? (5 Replies)
Discussion started by: zylwyz
5 Replies

8. Shell Programming and Scripting

background process

Hi, In shell script when I use script1 >> filelog the echo statments of script1 gets printed in the filelog but when I try to run script in background i.e, script1 & >> filelog nothing gets printed in the filelog. Anybody knows whats going on here. thanks (3 Replies)
Discussion started by: k_oops9
3 Replies

9. Shell Programming and Scripting

process in background

Hi Guys, I am facing some weird problem with my shell script. The script shows up a menu and for every ontion internally calls a shell script which start/stop various servers. When I am using '&' while calling the internal shell script so that the server run in the background. For exiting... (1 Reply)
Discussion started by: agoyal
1 Replies

10. Shell Programming and Scripting

capture the process id when starting a background process

Hello all, How do I start a background process and save the process id to a file on my system. For example %wait 5 & will execute and print the process id. I can't figure out how to get it to a file. I've tried: > filename 0>filename 1>filename. Any assistance is most appreciated. Thanks, Jim... (10 Replies)
Discussion started by: jleavitt
10 Replies
Login or Register to Ask a Question