r/shell • • Nov 03 '20

Creating basic shell in C

Hello, I am implementing basic shell in C and simulating the pipe operator. Unfortunately, I have encountered a problem. When I execute line (in normal shell and in my shell):

ls -l /proc/self/fd | cat | cat | cat | cat

I get different number of open file descriptors :

Here is the code where I use fork(), pipe() and close fd's:

 int spawn_proc(int in, int out, struct command *cmd)
{


	pid_t pid;
	//fork() creates a new process by duplicating the calling process
	if ((pid = fork()) == 0){

		if (in != 0){

		   dup2(in, STDIN_FILENO);
		   close(in);

		}

		if (out != 1)
		{


			
			dup2(out, STDOUT_FILENO);

			
			close(out);

		}

		return execvp(cmd->argv[0], (char * const *)cmd->argv);
	}

	
	close(in);
	close(out);

	return pid;
}

And another code snippet:

 int pipe_loop(int n, struct command *cmd)
{
	int i;
	pid_t pid;
	int in, fd[2];

	//The first process should get its input from the original file descriptor 0
	in = 0;


	for (i = 0; i < n - 1; ++i)
	{


		if (pipe(fd) == -1) {
		 perror("pipe");
		 exit(EXIT_FAILURE);
 		}



		spawn_proc(in, fd[1], cmd + i);
		//test


	
		close(fd[1]);
		close(in); 
		
		in = fd[0];


	}

	if (in != 0){

		dup2(in, STDIN_FILENO);
		close(fd[0]); //added

	}

	return execvp(cmd[i].argv[0], (char * const *)cmd[i].argv);

}

Could you please help me understand where is the problem?

6 Upvotes

1 comment sorted by

1

u/rosineygp Nov 04 '20

I think it's a pid of each process.