Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to pass the ls -la command from the child process to the parent process. I get an error. What am I doing wrong?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

int main()
{
	pid_t pid;
	int fd[2];
	char buffer[3];
	char *argv[3]= {"ls", "-la", NULL};
	buffer[3] = *argv[1000];
	
	if(pipe(fd)<0)
		printf("Cannot create pipe\n");
	
	int pipe_result;
	pipe_result =pipe(fd);
	if (pipe_result<0)
		printf("error");
	
	pid= fork();
	
	if(pid<0) {
		printf("Couldn't create child process, err =%d\n", pid);
		return -1;
	} else if (pid ==0) {
		close(fd[0]);
		write(fd[1], buffer, 1000);
		close(fd[1]);
		
	} else {
		close(fd[1]);
		read(fd[0], buffer, 1000);
		close(fd[0]);
		}

	
	return 0;
	}


What I have tried:

I have no other ideas
Posted
Updated 28-Apr-21 20:13pm

1 solution

Try
C
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>

const size_t BufSize = 1024;

int main()
{
  pid_t pid;
  int fd[2];

  char buffer[BufSize];

  const char * cmd = "ls -la";


  if(pipe(fd)<0)
    printf("Cannot create pipe\n");

  int pipe_result;
  pipe_result =pipe(fd);
  if (pipe_result<0)
    printf("error");

  pid= fork();

  if(pid<0) {
    printf("Couldn't create child process, err =%d\n", pid);
    return -1;
  } else if (pid ==0) {
    close(fd[0]);
    write(fd[1], cmd, strlen(cmd));
    close(fd[1]);

  } else
  {
    close(fd[1]);
    size_t nread = read(fd[0], buffer, BufSize);
    if (nread > 0)
    {
      for ( size_t n = 0; n < nread; ++n)
        putchar( buffer[n] );
      putchar('\n');
    }
    close(fd[0]);
  }
  return 0;
}
 
Share this answer
 
Comments
Rafał Kowalczyk 2021 29-Apr-21 3:49am    
Thank you for your response. However, I need the child process to execute the ls -la command and the parent process to display the command execution. Currently it only displays "ls -la".
CPallini 29-Apr-21 4:05am    
Well, that's up to you: now you know, at least, how to correctly pass info from the former to the latter.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900