fork(3) download
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/wait.h>
  6. #include <signal.h>
  7.  
  8. typedef void (*socket_handler)(int port);
  9.  
  10. void delay() {
  11. for (int i = 0; i < 10; i++)
  12. sleep(1);
  13. }
  14.  
  15. // Create and handle tcp socket connections
  16. void tcp_server(int port) {
  17. printf("TCP: %d\n", port);
  18.  
  19. // Just a delay to simulate a server
  20. delay();
  21.  
  22. exit(0);
  23. }
  24.  
  25. // Create and handle udp socket connections
  26. void udp_server(int port) {
  27. printf("UDP: %d\n", port);
  28.  
  29. // Just a delay to simulate a server
  30. delay();
  31.  
  32. exit(0);
  33. }
  34.  
  35. int start_process(int port, socket_handler handler) {
  36. pid_t pid;
  37.  
  38. pid = fork();
  39. if (pid < 0) {
  40. perror("fork()");
  41. return -1;
  42. }
  43.  
  44. if (pid == 0) {
  45. // Starting handler
  46. handler(port);
  47. }
  48.  
  49. return pid;
  50. }
  51.  
  52. int main(int argc, char *argv[]) {
  53. pid_t tcp_pid = start_process(2222, tcp_server);
  54. pid_t udp_pid = start_process(5555, udp_server);
  55.  
  56. printf("Process TCP pid: %d has started\n", tcp_pid);
  57. printf("Process UDP pid: %d has started\n", udp_pid);
  58.  
  59. // Simple way to finish both processes
  60. do {
  61. int status;
  62. pid_t finished_pid = waitpid(-1, &status, 0);
  63.  
  64. printf("Process %d finished\n", finished_pid);
  65.  
  66. if (finished_pid == tcp_pid)
  67. tcp_pid = -1;
  68. if (finished_pid == udp_pid)
  69. udp_pid = -1;
  70.  
  71. } while (tcp_pid != -1 || udp_pid != -1);
  72.  
  73. return 0;
  74. }
  75.  
Success #stdin #stdout 0s 2112KB
stdin
Standard input is empty
stdout
UDP: 5555
TCP: 2222
Process TCP pid: 31571 has started
Process UDP pid: 31572 has started
Process 31572 finished
Process 31571 finished