Sobes.tech
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:

  1. Files — processes write data to a shared file, and another process reads it.
  2. Channels (pipes) — a unidirectional or bidirectional stream of data between processes.
  3. Sockets — network connections that allow data exchange even between processes on different machines.
  4. Shared memory — a memory area allocated for quick data exchange accessible by multiple processes.
  5. Semaphores — used for synchronizing access to shared resources, preventing race conditions.
  6. Message queues — processes send and receive structured messages through a queue.
  7. 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;
}