C - fork() and sharing memory

后端 未结 3 710
甜味超标
甜味超标 2021-02-19 15:30

I need my parent and child process to both be able to read and write the same variable (of type int) so it is \"global\" between the two processes.

I\'m assuming this wo

3条回答
  •  梦谈多话
    2021-02-19 16:27

    Since you are mentioning using fork(), I assume that you are living on a *nix-System

    From Unix.com

    The primary way to share data between processes using UNIX IPCs are:

    (1) Shared memory;

    (2) Sockets:

    There are other UNIX IPCs including

    (3) Message Queues.

    (4) Semaphores;

    (5) Signals.

    Your best bet (for IPCs) is to use shared memory segments, based on your post. You might need to use semaphores to insure that the shared memory operations are atomic.

    A tutorial on forking and shared memory is on dev shed:

    http://forums.devshed.com/c-programming-42/posix-semaphore-example-using-fork-and-shared-memory-330419.html

    another more in-depth description of using multithreading (if appilcable for your application) can be found here:

    https://computing.llnl.gov/tutorials/pthreads/

提交回复
热议问题