I am in need of some help of understanding how to create one parent and three children and connecting pipes between the childrens.
My task is to get the first child to run ls -l /bin/?? and send it to the second child that will run grep rwxr-xr-x and send that to the third child that will run sort.
It wil look like this if typed in to bash:
ls -l /bin/?? | grep rwxr-xr-x | sort
My code right now:
#include <sys/wait.h>
#include <sys/types.h>
#inlcude <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define READ 0
#define WRITE 1
int main()
{
int fds[2], i;
pid_t pid;
pipe(fds);
for(i = 0; i < 3; i++)
{
pid = fork();
if(pid == (pid_t) 0)
if(i == 0)
{
/* First child */
}
else if(i == 1)
{
/* second child */
}
else if(i == 2)
{
/* Third child */
}
break;
else
{
/* This is the parent */
}
}
}
The problem is that i don't really know if this is the correct way of doing it.
Please avoid telling me to do this with threads as I am trying to learn pipes and communication between processes.
You are running a fork() in a loop. Every fork() will result in two processes. So total you are creating 8 processes. Need to take that fork() call out of the loop.
This is how fork works,
fork() [Process 1]
/\
/ \
[Process 1]fork() fork()[Process 2]
/\
/ \
[Process 2]fork() fork()[Process 3]
To achieve what you aspire try following code,
int main()
{
pid_t pid[3];
pid[0] = fork();
if( pid[0] == 0)
{
/* First Process */
pid[1] = fork();
if(pid[1] == 0)
{
/* First Process Continued. */
}
else
{
/* Second Process */
}
}
else
{
/* 3rd Process */
}
return 0;
}
Related
I have the following program, when I run the program, I feel really confused that why my program didn't excute
int num=i;
printf("it is No.%d !",num);
printf("hello , I will excute execvp!");
My program basically create 6 child processes to excute executionbode() function, and then use execvp to overload original program. However, everytime when I run the program, the string "hello, I will execute execvp" never shows up! Also I think those three sentences above also didn't execute in the running program? can someone tell me why? Here is my program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include "makeargv.h"
#include "redirection.h"
#include <sys/wait.h>
int executionnode(int i);
int main(){
pid_t childpid;
int i;
int row=6;
for(i=0;i<row;i++)
{ childpid=fork();
if(childpid==0)
continue;
else if (childpid>0)
executionnode(i);
else {
perror("something wrong");
exit(1);
}
}
}
int executionnode(int i){
sleep(i);
printf("hello, I am process:%ld\n",(long)getpid());
wait(NULL);
char *execArgs[] = { "echo", "Hello, World!", NULL };
int num=i;
printf("it is No.%d !",num);
printf("hello , I will excute execvp!");
execvp("echo", execArgs);
}
Can someone tell me why? and how to fix it? I feel it is really strange? Is it because of execvp() functions? I just began to learn operating system,so I am really confused about it! Thank you for helping me!
As user3629249 said you have some confusion. You'll get many children of children of children... and that wait(NULL) is useless :).
I used this structure to got your goal in my OS subject excercises.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#define N 5
int main(int argc, char const *argv[])
{
pid_t pid,pids[N];
int i, num_pids = 0;
int state = 0;
int prior[]={1,3,5,2,4};
pid_t parent_pid = getpid();
printf("Parent pid is %i\n",father_pid);
// This for loop is the key
for (i = 0; i < N && getppid() != parent_pid; i++)
{
if ((pid = fork()) < 0)
{
printf ("fork error\n");
exit(-1);
}
pids[num_pids++] = pid;
}
if (pid == 0) // Child processes
{
printf("I am the child %i\n",getpid());
}
else // Parent process
{
for (i = 0; i < N; i++)
{
int pid_index = prior[i]-1; // Array starts with 0
pid = waitpid(pids[pid_index]);
printf("Children %i ended\n",pids[indice_pid]);
printf("%i alive children\n",N-1-i);
}
}
return 0;
}
This structure works because you save the parent's pid in parent_pid variable and compare the parent of each process pid with getppid(). If this pid is different that parent_pid, this proccess is the parent. In another case the process is a child so it has to stop (these processes don't have to fork). With this way you can get only the forks you need.
The rest of the code is the same: Pid==0 is child process and any other is the parent. You can call executionnode(int i) in child processes block (remember, pid==0 !!! you have a mistake). i variable should have the right value in each call I think.
Good luck!
When a process sets the child subreaper bit with prctl(PR_SET_CHILD_SUBREAPER, 1) (documented here), does it need to use prctl(PR_SET_CHILD_SUBREAPER, 0) to clear it after a fork?
No, the child subreaper bit does not persist across forks.
The relevant Linux kernel code is in copy_signal() in kernel/fork.c: the signal struct is initialized to all zeros, and the is_child_subreaper bit is never set.
However, has_child_subreaper is set:
sig->has_child_subreaper = current->signal->has_child_subreaper ||
current->signal->is_child_subreaper;
This test program demonstrates the behavior:
#include <stdio.h>
#include <stdlib.h>
#include <sys/prctl.h>
int main(int argc, char** argv) {
int pid;
int i;
prctl(PR_SET_CHILD_SUBREAPER, 1);
prctl(PR_GET_CHILD_SUBREAPER, &i);
printf("Before fork: %d\n", i);
pid = fork();
if (pid < 0) {
return 1;
} else if (pid == 0) {
prctl(PR_GET_CHILD_SUBREAPER, &i);
printf("In child: %d\n", i);
return 0;
}
return 0;
}
Outputs:
Before fork: 1
In child: 0
I tried to redirect (write) a Unix command output to a shared memory segment in the child,
and then have the parent read the output back out from the same shared memory segment in the parent process. I don't have a lot of success after few futile attempts. Can anyone show me a way?
thanks in advance.
My code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main()
{
key_t key; int shmid; char* data;
pid_t cpid=fork();
if (cpid<0)
{
fprintf(stderr,"Fork error!\n");
exit (-1);
}
else if (cpid==0) // child process
{
if ((key = ftok("mysh.c", 'R')) == -1)
{
perror("ftok");
exit(1);
}
// Connect to shared memory
if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1)
{
perror("shmget");
exit(1);
}
// Attach to the segment
data = shmat(shmid, (void *) 0, 0);
if (data == (char *) (-1))
{
perror("shmat");
exit(1);
}
system("ls -l");
// Stuck: How to redirect the output of "ls -l"
// to a shared memmory segment "data", so that parent process
// can retrieve it later?? Tried to
// do pipe and dup2 but none worked.
// Attempt via read?, but only garbage
read(STDIN_FILENO, data, SHM_SIZE);
}
else
{ // parent process
int st;
wait(&st);
printf("Output read from the child:\n");
if ((write(STDOUT_FILENO, data, SHM_SIZE)) < 0 )
{
perror("write 2");
exit(1);
}
}
}
======================
system("ls -l");
// Stuck: How to redirect the output of "ls -l"
// to a shared memmory segment "data", so that parent process
// can retrieve it later?? Tried to
// do pipe and dup2 but none worked.
For test purpose, I suggest you read from stdin, then write them to data.
Here is an example using POSIX shared memory (POSIX IPC API is better than SYSV IPC API), which child read from stdin to a shared memory region, and parent write the content of this shared memory region to stdout:
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
const char *shm_name = "/dummy_cat_shm";
int shm_fd;
off_t shm_length;
const char *read_sem_name = "/dummy_cat_read";
const char *write_sem_name = "/dummy_cat_write";
sem_t *read_sem, *write_sem;
pid_t pid;
int buf_length;
char *write_ptr, *read_ptr;
buf_length = 1024;
shm_length = sizeof(buf_length) + buf_length;
/* Create semaphore */
read_sem = sem_open(read_sem_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR, 0);
if (read_sem == SEM_FAILED) {
perror("sem_open");
goto clean_up3;
}
write_sem = sem_open(write_sem_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR, 1);
if (write_sem == SEM_FAILED) {
perror("sem_open");
goto clean_up2;
}
/* Create shared memory segment */
shm_fd = shm_open(shm_name, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
if (shm_fd < 0) {
perror("shm_open");
goto clean_up1;
}
if (ftruncate(shm_fd, shm_length) < 0) {
perror("ftruncate");
goto clean_up0;
}
if ((pid = fork()) < 0) {
perror("fork");
goto clean_up0;
}
else if (pid == 0) {
write_ptr = mmap(NULL, shm_length, PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (write_ptr == MAP_FAILED) {
perror("mmap");
goto clean_up0;
}
char *buf = write_ptr+sizeof(buf_length);
while (sem_wait(write_sem) == 0) {
if (fgets(buf, buf_length, stdin) != NULL) {
*(int *)write_ptr = 1;
sem_post(read_sem);
}
else {
*(int *)write_ptr = 0;
sem_post(read_sem);
break;
}
}
munmap(write_ptr, shm_length);
}
else {
read_ptr = mmap(NULL, shm_length, PROT_READ, MAP_SHARED, shm_fd, 0);
if (read_ptr == MAP_FAILED) {
perror("mmap");
goto clean_up0;
}
char *buf = read_ptr + sizeof(buf_length);
while (sem_wait(read_sem) == 0) {
if (*(int *)read_ptr > 0) {
printf("%s", buf);
sem_post(write_sem);
}
else {
break;
}
}
munmap(read_ptr, shm_length);
}
clean_up0:
shm_unlink(shm_name);
clean_up1:
sem_unlink(write_sem_name);
clean_up2:
sem_unlink(read_sem_name);
clean_up3:
exit(EXIT_FAILURE);
}
Note: these two mmap() could be put before fork() in this case.
Compiling:
gcc shm_exp.c -pthread -lrt
Running:
$ ls / | ./a.out
bin/ home/ lib32/ mnt/ run/ sys/ vmlinuz#
boot/ initrd.img# lib64/ opt/ sbin/ tmp/ vmlinuz.old#
dev/ initrd.img.old# lost+found/ proc/ selinux/ usr#
etc/ lib/ media/ root/ srv/ var/
How to redirect stdout of the ls -l
We must shed more light on the processes (parent and children) involved into this code.
How many processes your program creates during its run?
The correct answer is - three.
Two processes are the parent and the explicitly forked child.
The third one is created by the system("ls -l") call.
This function implicitly forks another process that executes (by calling an exec family function) the "ls -l" sell command. What you need to redirect is the output of the child process created by the system() function. It is sad, but the system() does not establish IPC between the participators. If you need to manipulate with the output, do not use system().
I agree with #leeduhem, popen() could be the best approach.
It works exactly as the system(), i.e. forks a new process and executes "ls -l".
In addition, it also establishes a pipe IPC between the participators, so it is easy to catch the child output and to do with it whatever you want:
char buff[1024];
FILE *fd;
// instead of system("ls -l")
fd = popen("ls -l", "r");
// check for errors
while(fgets(buff, sizeof(buff), fd) != NULL)
{
// write to the shared memory
}
pclose(fd);
If you do not want to use the popen() function, you may write a similar one.
The general approach is
open a pipe()
fork() a new process
redirect stdout using dup2
call a suitable exec() function (probably execl()) executing "ls -l"
read from the descriptor you are duplicating by dup2.
i am trying to implement this linux command using C.
ls -l | cut -b 1
the way i am trying to do it is
calling ls -l in parent process
putting output of ls -l in a file(writing to a file)
calling cut in child process
reading the file (the one written in the parent process)
applying cut to the file
printing the output
this is by far what i have done
/* pipe.c */
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
void main()
{
int filedes[2];
int p;
pid_t pid, pid1;
p=pipe(filedes);
FILE *stream;
char buff[20];
printf("pipe command returns %d, %d ,%d\n",p, filedes[0],filedes[1]);
if(pipe(filedes) == -1) /* Create the pipe */
printf("error pipe");
pid1=fork();
pid=getpid();
switch (pid1) { /* Create a child process */
case -1:
printf("error fork");
case 0: /* Child */
/* Close unused write end */
/* Child can now read from pipe */
if (close(filedes[1]) == -1)
printf("error close");
printf("I am a child process pid %d, and will read from pipe\n",pid);
while (read(filedes[0], &buff, 1) > 0)
write(STDOUT_FILENO, &buff, 1);
write(STDOUT_FILENO, "\n", 1);
close(filedes[0]);
_exit(EXIT_SUCCESS);
break;
default: /* Parent */
/* Close unused read end */
/* Parent can now write to pipe */
if (close(filedes[0]) == -1)
printf("error close");
printf("I am the parent process pid %d, and will write to pipe\n", pid );
stream = fdopen(filedes[1], "w");
strcpy(buff, "This is a test\n");
write(filedes[1], buff, strlen(buff));
char *args[80];
args[0] = "ls";
args[1] = "-l";
args[2] = NULL;
execvp(args[0],args);
int bak, new;
bak = dup(1);
new = open("/home/urwa/abc.txt", O_WRONLY);
dup2(new, 1);
close(new);
close(filedes[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
break;
}
}
this piece of code works perfectly fine. and prints at stand output the test statement. as well as the ls -l output. but the file is empty. what am i doing wrong.
I also tried freopen as follow.. still empty file. :/
FILE *fp;
fp = freopen ("/temp/abc.txt", "a+", stdout);
You didn't called the cut in the child and also the file descriptors are messed up here.
For performing the task you have to close the stdout of parent and make the write end stdout in parent before execvp. In child you have to close stdin of child and make read end as stdin to your child before execvp. In that way your parent's stdout is stdin of your child(creating the pipe b/w two).
int main()
{
int filedes[2];
int p;
pid_t pid = 0, pid1 = 0;
p=pipe(filedes);
FILE *stream;
char buff[20];
char *args[80];
printf("pipe command returns %d, %d ,%d\n",p, filedes[0],filedes[1]);
if(pipe(filedes) == -1) /* Create the pipe */
printf("error pipe");
pid1=fork();
pid=getpid();
switch (pid1) { /* Create a child process */
case -1:
printf("error fork"); break;
case 0: /* Child */
/* Close unused write end */
/* Child can now read from pipe */
if (close(filedes[1]) == -1)
printf("error close");
printf("I am a child process pid %d, and will read from pipe\n",pid);
close(0); //close stdin of child
dup(filedes[0]); //make pipes read end stdin of child
args[0] = "cut";
args[1] = "-b";
args[2] = "1";
args[3] = NULL;
execvp(args[0],args);
break;
default: /* Parent */
/* Close unused read end */
/* Parent can now write to pipe */
if (close(filedes[0]) == -1)
printf("error close");
printf("I am the parent process pid %d, and will write to pipe\n", pid );
close(1); //close stdout
dup(filedes[1]); //make write end of pipe stdout of parent
args[0] = "ls";
args[1] = "-l";
args[2] = NULL;
execvp(args[0],args);
break;
}
}
how do I intercept calls made from other process which I have called from my process. (say - I call make and I would like to intercept and modify call to gcc from make).
Here is a small example with ptrace:
#include <unistd.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <sys/user.h>
#include <sys/prctl.h>
const char *sys_call_name(long num);
int main()
{
pid_t pid = fork();
struct user_regs_struct regs;
if (!pid) {
/* child */
while (1) { printf("C\n"); sleep(1); }
}
else { /* parent */
int status = 0;
ptrace(PTRACE_ATTACH, pid, NULL, 0);
ptrace(PTRACE_SETOPTIONS, pid, NULL, PTRACE_SYSCALL) ;
while (1) {
printf("waiting\n");
pid = wait(&status);
/* child gone */
//if (WIFEXITED(status)) { break; }
ptrace(PTRACE_GETREGS, pid, 0, ®s);
/* regs.orig_eax is the system call number */
printf("A system call: %d : %s\n", regs.orig_eax, sys_call_name(regs.orig_eax));
/* let child continue */
ptrace(PTRACE_SYSCALL, pid, NULL, 0);
}
}
return 0;
}
const char *sys_call_name(long num) {
switch(num) {
case 4: return "write";
case 162: return "nanosleep";
case 165: return "getresuid";
case 174: return "rt_sigaction";
case 175: return "rt_sigprocmask";
default: return "unknown";
}
}
It sound from your question that you are looking for Makefile help, specifically you are looking for doing something for all call to the c-compiler.
make allows for any command to be redefined locally -- all you have to do is redefine the macro in make -- for gcc you would simply redefine the CC macros.
You could do that from the command like, like
make CC=echo
which would substitute all call from gcc to echo (not very useful, but you get the idea).
Or you can do it in the Makefile by adding a line like
CC=echo
testprogram: testprogram.o
and when you do make testprogram the make will echo something rather than invoking gcc
You don't easily. The facility in question is the ptrace function, not for the faint of heart.