Safe utilization of fork() to create multiple children, without data races

I’m writing a small program which uses fork() to create 4 child threads. I am new to working with fork() and want to make certain I am using the most thread-safe approach. The issue I am having does not seem to have negative effects on the outcome but it does seem to indicate that there is some indeterminate behavior which I would like to address. Consider the code below:

pid_t pid = -2;
std::vector<pid_t> pids;
uint16_t nextPort = startingPort;
std::cout << "Creating " << noThreads << " threadsn";
for(int i = 0; i < noThreads; ++i)
{
    std::cout << i << "n";
    if(pid)
    {
        pid = fork();
        pids.push_back(pid);
        std::cout << "Created PID: " << (intmax_t)pid << "t" << pids.size() << " totaln";
    }
}

Program output:

Creating 4 threads
0
Created PID: 521042     1 total
1
Created PID: 521043     2 total
2
Created PID: 0  1 total
1
2
3
Created PID: 521044     3 total
3
Created PID: 0  2 total
2
3
Created PID: 0  3 total
Created PID: 521045     4 total
3
Cleaning up

The output varies but what appears to be consistently happening is that when a child is created by fork, there is a moment in time between when the new thread exists and the return value of fork() in the child process is set to zero, causing the logging to be indeterminate. At least that is what seems like is happening. However, strangely enough it doesn’t seem to be filling the vector with 0’s as I would expect.

Is there a more thread-safe way of implementing this, still us?

Full code below. please don’t beat me up on the clean-up. Still working on this.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
#include <string>
#include <unistd.h>
#include <signal.h>
#include <algorithm>
#include <atomic>
#include <iostream>
#include <cstdint>
#include <vector>

// An arbitrary port value for the first thread
// subsequent threads will each increment by 1
constexpr uint16_t startingPort = 7777;

// Number of children to fork
constexpr short noThreads = 4;

// UDP message buffer max size
constexpr uint8_t bufferSize = 60;

typedef std::atomic_int atomic_pid_t;
atomic_pid_t pid;

// Send a message to the local host on the post specified
void sendUdpMessage(std::string buffer, unsigned short port)
{
    int sock =  socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in addr;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    sendto(sock, buffer.c_str(), buffer.size(), 0, (const struct sockaddr *) &addr, sizeof(addr));
    close(sock);
}

int main(int argc, char** argv)
{
    // Fork n number of threads and store the child
    // PID's in a vector
    pid = -2;
    std::vector<pid_t> pids;
    uint16_t nextPort = startingPort;
    std::cout << "Creating " << noThreads << " threadsn";
    for(int i = 0; i < noThreads; ++i)
    {
        std::cout << i << "n";
        if(pid)
        {
            pid = fork();
            pids.push_back(pid);
            std::cout << "Created PID: " << (intmax_t)pid << "t" << pids.size() << " totaln";
        }
    }

    // While the vector of PID's is not empty, determine if
    // the current process PID is in the vector
    // if so, send a message.  increment the port value
    // erase the pid entry
    std::vector<pid_t>::iterator currentPos;
    while(pids.size() > 0)
    {
        currentPos = std::find(pids.begin(), pids.end(), pid);
        if(currentPos != pids.end())
        {
            char buffer[bufferSize];
            snprintf(buffer, bufferSize, "Writing buffer to port %hu from pid %hun", nextPort, (intmax_t)pid);
            sendUdpMessage(buffer, nextPort);
            ++nextPort;
            pids.erase(currentPos);
        }
    }

    switch(pid)
    {
        case -1:
            perror("fork");
            exit(EXIT_FAILURE);

        case 0:
            puts("Cleaning upn");
            for(auto it : pids)
            {
                kill(it, SIGINT);
            }
            exit(EXIT_SUCCESS);
    }
}

*** update ***

I still do not have a resolution but I tried something which I thought might work. It does not and I am if the problem is different then I suspected.

First off I did update the print statements to use std::endl which unfortunately did not help

The next thing i tried on the assumption that the child function begins executing before setting the return value. so I updated the if statement to

if(getppid() != pid && pid)
{
    pid = getpid()
    pid = fork()
    ...
}

However this also did not make a difference.

12

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật