File indexing completed on 2024-03-24 17:24:18

0001 /*****************************************************************************
0002  *   Copyright 2014 - 2015 Yichao Yu <yyc1992@gmail.com>                     *
0003  *                                                                           *
0004  *   This program is free software; you can redistribute it and/or modify    *
0005  *   it under the terms of the GNU Lesser General Public License as          *
0006  *   published by the Free Software Foundation; either version 2.1 of the    *
0007  *   License, or (at your option) version 3, or any later version accepted   *
0008  *   by the membership of KDE e.V. (or its successor approved by the         *
0009  *   membership of KDE e.V.), which shall act as a proxy defined in          *
0010  *   Section 6 of version 3 of the license.                                  *
0011  *                                                                           *
0012  *   This program is distributed in the hope that it will be useful,         *
0013  *   but WITHOUT ANY WARRANTY; without even the implied warranty of          *
0014  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU       *
0015  *   Lesser General Public License for more details.                         *
0016  *                                                                           *
0017  *   You should have received a copy of the GNU Lesser General Public        *
0018  *   License along with this library. If not,                                *
0019  *   see <http://www.gnu.org/licenses/>.                                     *
0020  *****************************************************************************/
0021 
0022 #include <qtcurve-utils/process.h>
0023 #include <assert.h>
0024 #include <unistd.h>
0025 #include <time.h>
0026 #include <signal.h>
0027 #include <sys/wait.h>
0028 
0029 int pipe_fds[2];
0030 long num;
0031 
0032 static void
0033 forkCb(void*)
0034 {
0035     write(pipe_fds[1], &num, sizeof(num));
0036 }
0037 
0038 static void
0039 sigchld_handler(int)
0040 {
0041     wait(nullptr);
0042 }
0043 
0044 int
0045 main()
0046 {
0047     int res = pipe(pipe_fds);
0048     assert(res == 0);
0049     srandom(time(nullptr));
0050     num = random();
0051 
0052     struct sigaction sa;
0053     memset(&sa, 0, sizeof(struct sigaction));
0054     sa.sa_handler = sigchld_handler;
0055     sigemptyset(&sa.sa_mask);
0056     sa.sa_flags = SA_RESTART;
0057     sigaction(SIGCHLD, &sa, nullptr);
0058 
0059     if (fork() == 0) {
0060         sleep(4);
0061         return 0;
0062     }
0063 
0064     alarm(1);
0065     bool fork_res = qtcForkBackground(forkCb, nullptr);
0066     assert(fork_res);
0067     long num_sent = 0;
0068     ssize_t read_res = read(pipe_fds[0], &num_sent, sizeof(num_sent));
0069     assert(read_res == sizeof(num_sent));
0070     assert(num_sent = num);
0071     return 0;
0072 }