The other day, I saw a blogger write a blog using a Q & A method: concatenate a lot of knowledge points in the form of a Q & A. I think this form is good, so it is easy to highlight the key points. I will try again later, write a blog, and review my understanding of IPC process communication.
Q: Where do these examples come from?
A: The document library from IBM. For details, refer to my article.
Bytes.
Q: Why do I have to write it again here?
A: The original IBM document is quite classic. I suggest you take a look at it here. However, some of the original documents in the document cannot be compiled, and you need to make proper modifications to run them. In addition, those examples are earlier, and the running results on the current system are not necessarily consistent with the article description. Finally, the original text is not detailed enough to explain the statements in the example. It is better to write it again to deepen your understanding of the example and learn more about programming.
Q: Why are there so many comments in the code?
A: I originally wanted to write less comments and write them in my own words. However, I found that the System Programming Manual provides a very good explanation and is very simplified, the instructions provided by other websites are not complete, so simply paste the manual content. So you will see more comments than the code... if you don't want to see the comments, directly stick the code to the local, and delete the comments at a glance.
Q: Can the example be compiled?
A: All of them are compiled by ourselves. Let's get started ~
IPC shared memory-System V programming example
This instance contains two programs: map_v_write.cpp and map_v_read.cpp. After compilation, create a file named myshm. This file is used to generate the IPC key, which is described in the Code. Then run the Write Program, then run the read program, and observe the results.
/* File: map_v_write.cpp Description: works with the map_v_read.cpp file to complete the V shared memory programming experiment * // # include <sys/IPC. h> // # include <sys/types. h> // The two headers commented out are the most basic of IPC, but in the SHM. # include <sys/SHM. h> // System V shared memory function shmget shmat shmdt # include <string. h> // memcpy # include <stdio. h> // perror # include <errno. h> // errno // structure data is used for communication in the shared memory. The typedef struct {char name [4]; int age ;}people; Main (INT argc, char ** argv) {int shm_id, I; key_t key; // Save the return value of the ftok function char temp; People * p_map; // create an IPC key value char * name = ". /myshm "; // specify the existing file key = ftok (name, 1); // do not use 0/* Man ftok for parameters: name ftok-generate an IPC keysynopsis # include <sys/IPC. h> key_t ftok (const char * path, int ID); description the ftok () function returns a key based on path and ID that is usable in subsequent callto msgget (2 ), semget (2) and shmget (2 ). the path argument must be the pathname of an existing file that the process is able to stat (2 ). the ftok () function will return the same key value for all paths that name the same file, when called with the same ID value, and will return different key values when called with different ID values. if the file named by path is removed while still referred to by a key, a call to ftok () with the same path and ID returns an error. if the same file is recreated, then a call to ftok () with the same path and ID is likely to return a dif-ferent key. only the low order 8-bits of ID are significant. the behavior of ftok () is unspecified if these bits are 0. return values upon successful completion, ftok () returns a key. other-wise, ftok () returns (key_t)-1 and sets errno to indicate the error. */perror ("ftok:"); // print errno. For details, refer to errno definition in Appendix/* Man perrorname perror, errno-print system error messagessynopsis # include <stdio. h> void perror (const char * s); # include <errno. h> int errno; description the perror () function produces a message on the standard error output (file descriptor 2) describing the last error encountered during a call to a system or library function. the argument string S is printed, followed by a colon and a blank, followed by the message and a newline character. if S is a null pointer or points to a null string, the colon is not printed. the argument string shocould include the name of the program that incurred the error. the error number is taken from the external variable errno, Which is set when errors occur but not cleared when non-erroneous CILS are made. see intro (2 ). * /// obtain the shared memory ID shm_id = shmget (Key, 4096, ipc_creat | 00666); // give the permissions perror ("shmget:");/* Man shmget: name shmget-get shared memory segment identifiersynopsis # include <sys/types. h> # include <sys/IPC. h> # include <sys/SHM. h> int shmget (key_t key, size_t size, int shmflg); description the shmget () function returns the shared memory identifier associated with key. A shared memory identifier and associated data structure and shared memory segment of at least size bytes (see intro (2) are created for key if one of the following are true: O the key argument is equal to ipc_private. O the key argument does not already have a shared memory identifier associated with it, and (shmflg & ipc_creat) is true. upon creation, the data structure associated with the new Shared Memory identifier is initialized as follows: o the values of shm_perm.cuid, shm_perm.uid, shm_perm.cgid, and shm_perm.gid are set equal to the specified tive user ID and valid tive group ID, respec-tively, of the calling process. o The access permission bits of shm_perm.mode are set equal to the access permission bits of shmflg. shm_segsz is set equal to the value of size. o The values of shm_lpid, shm_nattch shm_atime, and shm_dtime are set equal to 0. o The shm_ctime is set equal to the current time. shared Memory segments must be explicitly removed after the last reference to them has been removed. return values upon successful completion, a non-negative integer representing a shared memory identifier is returned. other-wise,-1 is returned and errno is set to indicate the error. */p_map = (People *) shmat (shm_id, null, 0); perror ("shmat:");/* Name shmop, shmat, shmdt-shared memory operationssynopsis # include <sys/types. h> # include <sys/SHM. h> void * shmat (INT shmid, const void * shmaddr, int shmflg); default int shmdt (char * shmaddr); Standard conforming int shmdt (const void * shmaddr ); description The shmat () function attaches the shared memory segment associated with the shared memory identifier specified by shmid to the Data Segment of the calling process. * /// write data to the memory temp = 'a'; for (I = 0; I <10; I ++) {temp + = 1; memcpy (* (p_map + I )). name, & temp, 1); (* (p_map + I )). age = 20 + I;} // unlink shared memory shmdt (char *) p_map); // here you can remove char * for compilation and try it. After I remove it, the compilation fails, perror ("shmdt:");/* The shmdt () function detaches from the calling process's data segment the shared memory segment located at the address specified by shmaddr. if the application is standard-conforming (see standards (5), the shmaddr argument is of Type const void *. otherwise it is of type char *. */}
The APIs used by the read-End program are the same as those used by the write end, so the comments are omitted.
/* File: map_v_read.cpp Description: works with the map_v_write.cpp file to complete the V shared memory programming experiment */# include <sys/SHM. h> # include <unistd. h> # include <string. h> # include <stdio. h> // The read end program must be consistent with the write end program to communicate with each other // define the data structure typedef struct {char name [4]; int age;} people; main (INT argc, char ** argv) {int shm_id, I; key_t key; People * p_map; // create SHM file and get key char * name = ". /myshm "; Key = ftok (name, 1); perror (" ftok: "); // get SHM shm_id = shmget (Key, 4096, ipc_creat ); perror ("shmget:"); // link the SHM p_map = (People *) shmat (shm_id, null, 0); perror ("shmat :"); for (I = 0; I <10; I ++) {printf ("Name: % s \ n", (* (p_map + I )). name); printf ("Age % d \ n", (* (p_map + I )). age) ;}// unlink shmdt (char *) p_map); perror ("shmdt :");}
Finally, paste the errno. h definition to find the cause of the error.
#define EPERM 1 /* Not super-user */#define ENOENT 2 /* No such file or directory */#define ESRCH 3 /* No such process */#define EINTR 4 /* interrupted system call */#define EIO 5 /* I/O error */#define ENXIO 6 /* No such device or address */#define E2BIG 7 /* Arg list too long */#define ENOEXEC 8 /* Exec format error */#define EBADF 9 /* Bad file number */#define ECHILD 10 /* No children */#define EAGAIN 11 /* Resource temporarily unavailable */#define ENOMEM 12 /* Not enough core */#define EACCES 13 /* Permission denied */#define EFAULT 14 /* Bad address */#define ENOTBLK 15 /* Block device required */#define EBUSY 16 /* Mount device busy */#define EEXIST 17 /* File exists */#define EXDEV 18 /* Cross-device link */#define ENODEV 19 /* No such device */#define ENOTDIR 20 /* Not a directory */#define EISDIR 21 /* Is a directory */#define EINVAL 22 /* Invalid argument */#define ENFILE 23 /* File table overflow */#define EMFILE 24 /* Too many open files */#define ENOTTY 25 /* Inappropriate ioctl for device */#define ETXTBSY 26 /* Text file busy */#define EFBIG 27 /* File too large */#define ENOSPC 28 /* No space left on device */#define ESPIPE 29 /* Illegal seek */#define EROFS 30 /* Read only file system */#define EMLINK 31 /* Too many links */#define EPIPE 32 /* Broken pipe */#define EDOM 33 /* Math arg out of domain of func */#define ERANGE 34 /* Math result not representable */#define ENOMSG 35 /* No message of desired type */#define EIDRM 36 /* Identifier removed */#define ECHRNG 37 /* Channel number out of range */#define EL2NSYNC 38 /* Level 2 not synchronized */#define EL3HLT 39 /* Level 3 halted */#define EL3RST 40 /* Level 3 reset */#define ELNRNG 41 /* Link number out of range */#define EUNATCH 42 /* Protocol driver not attached */#define ENOCSI 43 /* No CSI structure available */#define EL2HLT 44 /* Level 2 halted */#define EDEADLK 45 /* Deadlock condition. */#define ENOLCK 46 /* No record locks available. */#define ECANCELED 47 /* Operation canceled */#define ENOTSUP 48 /* Operation not supported *//* Filesystem Quotas */#define EDQUOT 49 /* Disc quota exceeded *//* Convergent Error Returns */#define EBADE 50 /* invalid exchange */#define EBADR 51 /* invalid request descriptor */#define EXFULL 52 /* exchange full */#define ENOANO 53 /* no anode */#define EBADRQC 54 /* invalid request code */#define EBADSLT 55 /* invalid slot */#define EDEADLOCK 56 /* file locking deadlock error */#define EBFONT 57 /* bad font file fmt *//* Interprocess Robust Locks */#define EOWNERDEAD 58 /* process died with the lock */#define ENOTRECOVERABLE 59 /* lock is not recoverable *//* stream problems */#define ENOSTR 60 /* Device not a stream */#define ENODATA 61 /* no data (for no delay io) */#define ETIME 62 /* timer expired */#define ENOSR 63 /* out of streams resources */#define ENONET 64 /* Machine is not on the network */#define ENOPKG 65 /* Package not installed */#define EREMOTE 66 /* The object is remote */#define ENOLINK 67 /* the link has been severed */#define EADV 68 /* advertise error */#define ESRMNT 69 /* srmount error */#define ECOMM 70 /* Communication error on send */#define EPROTO 71 /* Protocol error *//* Interprocess Robust Locks */#define ELOCKUNMAPPED 72 /* locked lock was unmapped */#define ENOTACTIVE 73 /* Facility is not active */#define EMULTIHOP 74 /* multihop attempted */#define EBADMSG 77 /* trying to read unreadable message */#define ENAMETOOLONG 78 /* path name is too long */#define EOVERFLOW 79 /* value too large to be stored in data type */#define ENOTUNIQ 80 /* given log. name not unique */#define EBADFD 81 /* f.d. invalid for this operation */#define EREMCHG 82 /* Remote address changed *//* shared library problems */#define ELIBACC 83 /* Can't access a needed shared lib. */#define ELIBBAD 84 /* Accessing a corrupted shared lib. */#define ELIBSCN 85 /* .lib section in a.out corrupted. */#define ELIBMAX 86 /* Attempting to link in too many libs. */#define ELIBEXEC 87 /* Attempting to exec a shared library. */#define EILSEQ 88 /* Illegal byte sequence. */#define ENOSYS 89 /* Unsupported file system operation */#define ELOOP 90 /* Symbolic link loop */#define ERESTART 91 /* Restartable system call */#define ESTRPIPE 92 /* if pipe/FIFO, don't sleep in stream head */#define ENOTEMPTY 93 /* directory not empty */#define EUSERS 94 /* Too many users (for UFS) *//* BSD Networking Software */ /* argument errors */#define ENOTSOCK 95 /* Socket operation on non-socket */#define EDESTADDRREQ 96 /* Destination address required */#define EMSGSIZE 97 /* Message too long */#define EPROTOTYPE 98 /* Protocol wrong type for socket */#define ENOPROTOOPT 99 /* Protocol not available */#define EPROTONOSUPPORT 120 /* Protocol not supported */#define ESOCKTNOSUPPORT 121 /* Socket type not supported */#define EOPNOTSUPP 122 /* Operation not supported on socket */#define EPFNOSUPPORT 123 /* Protocol family not supported */#define EAFNOSUPPORT 124 /* Address family not supported by */ /* protocol family */#define EADDRINUSE 125 /* Address already in use */#define EADDRNOTAVAIL 126 /* Can't assign requested address */ /* operational errors */#define ENETDOWN 127 /* Network is down */#define ENETUNREACH 128 /* Network is unreachable */#define ENETRESET 129 /* Network dropped connection because */ /* of reset */#define ECONNABORTED 130 /* Software caused connection abort */#define ECONNRESET 131 /* Connection reset by peer */#define ENOBUFS 132 /* No buffer space available */#define EISCONN 133 /* Socket is already connected */#define ENOTCONN 134 /* Socket is not connected *//* XENIX has 135 - 142 */#define ESHUTDOWN 143 /* Can't send after socket shutdown */#define ETOOMANYREFS 144 /* Too many references: can't splice */#define ETIMEDOUT 145 /* Connection timed out */#define ECONNREFUSED 146 /* Connection refused */#define EHOSTDOWN 147 /* Host is down */#define EHOSTUNREACH 148 /* No route to host */#define EWOULDBLOCK EAGAIN#define EALREADY 149 /* operation already in progress */#define EINPROGRESS 150 /* operation now in progress *//* SUN Network File System */#define ESTALE 151 /* Stale NFS file handle */