Example input
Fork
Child pid == 0
Parent pid > 0
Error pid < 0
Waiting for child to finish (waitpid functionality and it’s arguments)
ececvp function
Communicating between processes
Pipes (parent-child communications) - example, must be opened before the fork
Signals - kill
files
Example output
# Fork
- `fork()` is a system call used for creating a new process (child process) by duplicating the calling process (parent process).
- The child process gets its own memory space and can execute a different code path from the parent process.
- `fork()` returns different values to the parent and child processes:
- Child pid == 0
- Parent pid > 0
- Error pid < 0
- Both the parent and child processes continue executing from the line of code immediately following the `fork()` call. However, they can distinguish themselves by checking the return value of `fork()`.
# Communicating between processes
## Pipes
- Pipes are a method of communication between two processes, where one process writes to a pipe and the other reads from the pipe.
- In Unix-like systems, pipes are created using the `pipe()` system call.
- Pipes are a one-way communication channel, so to enable two-way communication, two pipes must be used.
- Pipes can be used for parent-child communications, where the child process writes to the pipe and the parent process reads from the pipe.
- Example of using pipes for parent-child communication:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int fd[2];
pid_t pid;
char buffer[20];
if (pipe(fd) < 0) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) { // child process
close(fd[0]); // close unused read end
write(fd[1], "Hello, parent!", 14);
close(fd[1]); // close write end
} else { // parent process
close(fd[1]); // close unused write end
read(fd[0], buffer, sizeof(buffer));
printf("Received message: %s\n", buffer);
close(fd[0]); // close read end
}
return 0;
}
....