Junior — Middle
In what ways can processes exchange data and coordinate their actions?
sobes.tech AI
Answer from AI
Processes can exchange data and coordinate their actions in the following ways:
- Files — processes write data to a shared file, and another process reads it.
- Channels (pipes) — a unidirectional or bidirectional stream of data between processes.
- Sockets — network connections that allow data exchange even between processes on different machines.
- Shared memory — a memory area allocated for quick data exchange accessible by multiple processes.
- Semaphores — used for synchronizing access to shared resources, preventing race conditions.
- Message queues — processes send and receive structured messages through a queue.
- Signals — asynchronous notifications about events, such as termination or interruption.
Example of using pipe in C:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
int main() {
int fd[2];
pipe(fd);
if (fork() == 0) {
// Child process
close(fd[0]);
char msg[] = "Hello from child process!";
write(fd[1], msg, strlen(msg));
close(fd[1]);
} else {
// Parent process
close(fd[1]);
char buffer[100];
int n = read(fd[0], buffer, sizeof(buffer)-1);
buffer[n] = '\0';
printf("Received: %s\n", buffer);
close(fd[0]);
}
return 0;
}