導航:首頁 > 編程系統 > linuxcmsgget

linuxcmsgget

發布時間:2024-09-27 12:29:14

linux下c的兩個進程如何實現通信一個進程給另一個進程發送消息,另一個接受並顯示出來。求大神啊

linux中的進程通信分為三個部分:低級通信,管道通信和進程間通信IPC(inter process communication)。linux的低級通信主要用來傳遞進程的控制信號——文件鎖和軟中斷信號機制。linux的進程間通信IPC有三個部分——①信號量,②共享內存和③消息隊列。以下是我編寫的linux進程通信的C語言實現代碼。操作系統為redhat9.0,編輯器為vi,編譯器採用gcc。下面所有實現代碼均已經通過測試,運行無誤。

一.低級通信--信號通信

signal.c

#include <signal.h>
#include <stdio.h>
#include <unistd.h>

/*捕捉到信號sig之後,執行預先預定的動作函數*/
void sig_alarm(int sig)
{
printf("---the signal received is %d. /n", sig);
signal(SIGINT, SIG_DFL); //SIGINT終端中斷信號,SIG_DFL:恢復默認行為,SIN_IGN:忽略信號
}

int main()
{
signal(SIGINT, sig_alarm);//捕捉終端中斷信號
while(1)
{
printf("waiting here!/n");
sleep(1);
}
return 0;
}

二.管道通信

pipe.c

#include <stdio.h>
#define BUFFER_SIZE 30

int main()
{
int x;
int fd[2];
char buf[BUFFER_SIZE];
char s[BUFFER_SIZE];
pipe(fd);//創建管道
while((x=fork())==-1);//創建管道失敗時,進入循環

/*進入子進程,子進程向管道中寫入一個字元串*/
if(x==0)
{
sprintf(buf,"This is an example of pipe!/n");
write(fd[1],buf,BUFFER_SIZE);
exit(0);
}

/*進入父進程,父進程從管道的另一端讀出剛才寫入的字元串*/
else
{
wait(0);//等待子進程結束
read(fd[0],s,BUFFER_SIZE);//讀出字元串,並將其儲存在char s[]中
printf("%s",s);//列印字元串
}
return 0;
}

三.進程間通信——IPC

①信號量通信

sem.c

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

/*聯合體變數*/
union semun
{
int val; //信號量初始值
struct semid_ds *buf;
unsigned short int *array;
struct seminfo *__buf;
};

/*函數聲明,信號量定義*/
static int set_semvalue(void); //設置信號量
static void del_semvalue(void);//刪除信號量
static int semaphore_p(void); //執行P操作
static int semaphore_v(void); //執行V操作
static int sem_id; //信號量標識符

int main(int argc, char *argv[])
{
int i;
int pause_time;
char op_char = 'O';
srand((unsigned int)getpid());
sem_id = semget((key_t)1234, 1, 0666 | IPC_CREAT);//創建一個信號量,IPC_CREAT表示創建一個新的信號量

/*如果有參數,設置信號量,修改字元*/
if (argc > 1)
{
if (!set_semvalue())
{
fprintf(stderr, "Failed to initialize semaphore/n");
exit(EXIT_FAILURE);
}
op_char = 'X';
sleep(5);
}
for(i = 0; i < 10; i++)
{

/*執行P操作*/
if (!semaphore_p())
exit(EXIT_FAILURE);
printf("%c", op_char);
fflush(stdout);
pause_time = rand() % 3;
sleep(pause_time);
printf("%c", op_char);
fflush(stdout);

/*執行V操作*/
if (!semaphore_v())
exit(EXIT_FAILURE);
pause_time = rand() % 2;
sleep(pause_time);
}
printf("/n%d - finished/n", getpid());
if (argc > 1)
{
sleep(10);
del_semvalue(); //刪除信號量
}
exit(EXIT_SUCCESS);
}

/*設置信號量*/
static int set_semvalue(void)
{
union semun sem_union;
sem_union.val = 1;
if (semctl(sem_id, 0, SETVAL, sem_union) == -1)
return(0);

return(1);
}

/*刪除信號量*/
static void del_semvalue(void)
{
union semun sem_union;
if (semctl(sem_id, 0, IPC_RMID, sem_union) == -1)
fprintf(stderr, "Failed to delete semaphore/n");
}

/*執行P操作*/
static int semaphore_p(void)
{
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = -1; /* P() */
sem_b.sem_flg = SEM_UNDO;
if (semop(sem_id, &sem_b, 1) == -1)
{
fprintf(stderr, "semaphore_p failed/n");
return(0);
}
return(1);
}

/*執行V操作*/
static int semaphore_v(void)
{
struct sembuf sem_b;
sem_b.sem_num = 0;
sem_b.sem_op = 1; /* V() */
sem_b.sem_flg = SEM_UNDO;
if (semop(sem_id, &sem_b, 1) == -1)
{
fprintf(stderr, "semaphore_v failed/n");
return(0);
}
return(1);
}

②消息隊列通信

send.c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX_TEXT 512

/*用於消息收發的結構體--my_msg_type:消息類型,some_text:消息正文*/
struct my_msg_st
{
long int my_msg_type;
char some_text[MAX_TEXT];
};

int main()
{
int running = 1;//程序運行標識符
struct my_msg_st some_data;
int msgid;//消息隊列標識符
char buffer[BUFSIZ];

/*創建與接受者相同的消息隊列*/
msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
if (msgid == -1)
{
fprintf(stderr, "msgget failed with error: %d/n", errno);
exit(EXIT_FAILURE);
}

/*向消息隊列中發送消息*/
while(running)
{
printf("Enter some text: ");
fgets(buffer, BUFSIZ, stdin);
some_data.my_msg_type = 1;
strcpy(some_data.some_text, buffer);
if (msgsnd(msgid, (void *)&some_data, MAX_TEXT, 0) == -1)
{
fprintf(stderr, "msgsnd failed/n");
exit(EXIT_FAILURE);
}
if (strncmp(buffer, "end", 3) == 0)
{
running = 0;
}
}
exit(EXIT_SUCCESS);
}

receive.c

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

/*用於消息收發的結構體--my_msg_type:消息類型,some_text:消息正文*/
struct my_msg_st
{
long int my_msg_type;
char some_text[BUFSIZ];
};

int main()
{
int running = 1;//程序運行標識符
int msgid; //消息隊列標識符
struct my_msg_st some_data;
long int msg_to_receive = 0;//接收消息的類型--0表示msgid隊列上的第一個消息

/*創建消息隊列*/
msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
if (msgid == -1)
{
fprintf(stderr, "msgget failed with error: %d/n", errno);
exit(EXIT_FAILURE);
}

/*接收消息*/
while(running)
{
if (msgrcv(msgid, (void *)&some_data, BUFSIZ,msg_to_receive, 0) == -1)
{
fprintf(stderr, "msgrcv failed with error: %d/n", errno);
exit(EXIT_FAILURE);
}
printf("You wrote: %s", some_data.some_text);
if (strncmp(some_data.some_text, "end", 3) == 0)
{
running = 0;
}
}

/*刪除消息隊列*/
if (msgctl(msgid, IPC_RMID, 0) == -1)
{
fprintf(stderr, "msgctl(IPC_RMID) failed/n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}

③共享內存通信

share.h

#define TEXT_SZ 2048 //申請共享內存大小
struct shared_use_st
{
int written_by_you; //written_by_you為1時表示有數據寫入,為0時表示數據已經被消費者提走
char some_text[TEXT_SZ];
};

procer.c

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "share.h"

int main()
{
int running = 1; //程序運行標志位
void *shared_memory = (void *)0;
struct shared_use_st *shared_stuff;
char buffer[BUFSIZ];
int shmid; //共享內存標識符

/*創建共享內存*/
shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shmid == -1)
{
fprintf(stderr, "shmget failed/n");
exit(EXIT_FAILURE);
}

/*將共享內存連接到一個進程的地址空間中*/
shared_memory = shmat(shmid, (void *)0, 0);//指向共享內存第一個位元組的指針
if (shared_memory == (void *)-1)
{
fprintf(stderr, "shmat failed/n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X/n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;

/*生產者寫入數據*/
while(running)
{
while(shared_stuff->written_by_you == 1)
{
sleep(1);
printf("waiting for client.../n");
}
printf("Enter some text: ");
fgets(buffer, BUFSIZ, stdin);
strncpy(shared_stuff->some_text, buffer, TEXT_SZ);
shared_stuff->written_by_you = 1;
if (strncmp(buffer, "end", 3) == 0)
{
running = 0;
}
}

/*該函數用來將共享內存從當前進程中分離,僅使得當前進程不再能使用該共享內存*/
if (shmdt(shared_memory) == -1)
{
fprintf(stderr, "shmdt failed/n");
exit(EXIT_FAILURE);
}
printf("procer exit./n");
exit(EXIT_SUCCESS);
}

customer.c

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "share.h"

int main()
{
int running = 1;//程序運行標志位
void *shared_memory = (void *)0;
struct shared_use_st *shared_stuff;
int shmid; //共享內存標識符
srand((unsigned int)getpid());

/*創建共享內存*/
shmid = shmget((key_t)1234, sizeof(struct shared_use_st), 0666 | IPC_CREAT);
if (shmid == -1)
{
fprintf(stderr, "shmget failed/n");
exit(EXIT_FAILURE);
}

/*將共享內存連接到一個進程的地址空間中*/
shared_memory = shmat(shmid, (void *)0, 0);//指向共享內存第一個位元組的指針
if (shared_memory == (void *)-1)
{
fprintf(stderr, "shmat failed/n");
exit(EXIT_FAILURE);
}
printf("Memory attached at %X/n", (int)shared_memory);
shared_stuff = (struct shared_use_st *)shared_memory;
shared_stuff->written_by_you = 0;

/*消費者讀取數據*/
while(running)
{
if (shared_stuff->written_by_you)
{
printf("You wrote: %s", shared_stuff->some_text);
sleep( rand() % 4 );
shared_stuff->written_by_you = 0;
if (strncmp(shared_stuff->some_text, "end", 3) == 0)
{
running = 0;
}
}
}

/*該函數用來將共享內存從當前進程中分離,僅使得當前進程不再能使用該共享內存*/
if (shmdt(shared_memory) == -1)
{
fprintf(stderr, "shmdt failed/n");
exit(EXIT_FAILURE);
}

/*將共享內存刪除,所有進程均不能再訪問該共享內存*/
if (shmctl(shmid, IPC_RMID, 0) == -1)
{
fprintf(stderr, "shmctl(IPC_RMID) failed/n");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}

摘自:http://blog.csdn.net/piaojun_pj/article/details/5943736

Ⅱ 列舉幾種系統調用

操作系統實現的所有系統調用所構成的集合即程序介面或應用編程介面(Application Programming Interface,API)。是應用程序同系統之間的介面。
Linux系統調用,包含了大部分常用系統調用和由系統調用派生出的的函數。
一、進程式控制制:
fork 創建一個新進程
clone 按指定條件創建子進程
execve 運行可執行文件
exit 中止進程
_exit 立即中止當前進程
getdtablesize 進程所能打開的最大文件數
getpgid 獲取指定進程組標識號
setpgid 設置指定進程組標志號
getpgrp 獲取當前進程組標識號
setpgrp 設置當前進程組標志號
getpid 獲取進程標識號
getppid 獲取父進程標識號
getpriority 獲取調度優先順序
setpriority 設置調度優先順序
modify_ldt 讀寫進程的本地描述表
nanosleep 使進程睡眠指定的時間
nice 改變分時進程的優先順序
pause 掛起進程,等待信號
personality 設置進程運行域
prctl 對進程進行特定操作
ptrace 進程跟蹤
sched_get_priority_max 取得靜態優先順序的上限
sched_get_priority_min 取得靜態優先順序的下限
sched_getparam 取得進程的調度參數
sched_getscheler 取得指定進程的調度策略
sched_rr_get_interval 取得按RR演算法調度的實時進程的時間片長度
sched_setparam 設置進程的調度參數
sched_setscheler 設置指定進程的調度策略和參數
sched_yield 進程主動讓出處理器,並將自己等候調度隊列隊尾
vfork 創建一個子進程,以供執行新程序,常與execve等同時使用
wait 等待子進程終止
wait3 參見wait
waitpid 等待指定子進程終止
wait4 參見waitpid
capget 獲取進程許可權
capset 設置進程許可權
getsid 獲取會晤標識號
setsid 設置會晤標識號
二、文件系統控制
1、文件讀寫操作
fcntl 文件控制
open 打開文件
creat 創建新文件
close 關閉文件描述字
read 讀文件
write 寫文件
readv 從文件讀入數據到緩沖數組中
writev 將緩沖數組里的數據寫入文件
pread 對文件隨機讀
pwrite 對文件隨機寫
lseek 移動文件指針
_llseek 在64位地址空間里移動文件指針
p 復制已打開的文件描述字
p2 按指定條件復制文件描述字
flock 文件加/解鎖
poll I/O多路轉換
truncate 截斷文件
ftruncate 參見truncate
umask 設置文件許可權掩碼
fsync 把文件在內存中的部分寫回磁碟
2、文件系統操作
access 確定文件的可存取性
chdir 改變當前工作目錄
fchdir 參見chdir
chmod 改變文件方式
fchmod 參見chmod
chown 改變文件的屬主或用戶組
fchown 參見chown
lchown 參見chown
chroot 改變根目錄
stat 取文件狀態信息
lstat 參見stat
fstat 參見stat
statfs 取文件系統信息
fstatfs 參見statfs
readdir 讀取目錄項
getdents 讀取目錄項
mkdir 創建目錄
mknod 創建索引節點
rmdir 刪除目錄
rename 文件改名
link 創建鏈接
symlink 創建符號鏈接
unlink 刪除鏈接
readlink 讀符號鏈接的值
mount 安裝文件系統
umount 卸下文件系統
ustat 取文件系統信息
utime 改變文件的訪問修改時間
utimes 參見utime
quotactl 控制磁碟配額
三、系統控制
ioctl I/O總控制函數
_sysctl 讀/寫系統參數
acct 啟用或禁止進程記賬
getrlimit 獲取系統資源上限
setrlimit 設置系統資源上限
getrusage 獲取系統資源使用情況
uselib 選擇要使用的二進制函數庫
ioperm 設置埠I/O許可權
iopl 改變進程I/O許可權級別
outb 低級埠操作
reboot 重新啟動
swapon 打開交換文件和設備
swapoff 關閉交換文件和設備
bdflush 控制bdflush守護進程
sysfs 取核心支持的文件系統類型
sysinfo 取得系統信息
adjtimex 調整系統時鍾
alarm 設置進程的鬧鍾
getitimer 獲取計時器值
setitimer 設置計時器值
gettimeofday 取時間和時區
settimeofday 設置時間和時區
stime 設置系統日期和時間
time 取得系統時間
times 取進程運行時間
uname 獲取當前UNIX系統的名稱、版本和主機等信息
vhangup 掛起當前終端
nfsservctl 對NFS守護進程進行控制
vm86 進入模擬8086模式
create_mole 創建可裝載的模塊項
delete_mole 刪除可裝載的模塊項
init_mole 初始化模塊
query_mole 查詢模塊信息
*get_kernel_syms 取得核心符號,已被query_mole代替
四、內存管理
brk 改變數據段空間的分配
sbrk 參見brk
mlock 內存頁面加鎖
munlock 內存頁面解鎖
mlockall 調用進程所有內存頁面加鎖
munlockall 調用進程所有內存頁面解鎖
mmap 映射虛擬內存頁
munmap 去除內存頁映射
mremap 重新映射虛擬內存地址
msync 將映射內存中的數據寫回磁碟
mprotect 設置內存映像保護
getpagesize 獲取頁面大小
sync 將內存緩沖區數據寫回硬碟
cacheflush 將指定緩沖區中的內容寫回磁碟
五、網路管理
getdomainname 取域名
setdomainname 設置域名
gethostid 獲取主機標識號
sethostid 設置主機標識號
gethostname 獲取本主機名稱
sethostname 設置主機名稱
六、socket控制
socketcall socket系統調用
socket 建立socket
bind 綁定socket到埠
connect 連接遠程主機
accept 響應socket連接請求
send 通過socket發送信息
sendto 發送UDP信息
sendmsg 參見send
recv 通過socket接收信息
recvfrom 接收UDP信息
recvmsg 參見recv
listen 監聽socket埠
select 對多路同步I/O進行輪詢
shutdown 關閉socket上的連接
getsockname 取得本地socket名字
getpeername 獲取通信對方的socket名字
getsockopt 取埠設置
setsockopt 設置埠參數
sendfile 在文件或埠間傳輸數據
socketpair 創建一對已聯接的無名socket
七、用戶管理
getuid 獲取用戶標識號
setuid 設置用戶標志號
getgid 獲取組標識號
setgid 設置組標志號
getegid 獲取有效組標識號
setegid 設置有效組標識號
geteuid 獲取有效用戶標識號
seteuid 設置有效用戶標識號
setregid 分別設置真實和有效的的組標識號
setreuid 分別設置真實和有效的用戶標識號
getresgid 分別獲取真實的,有效的和保存過的組標識號
setresgid 分別設置真實的,有效的和保存過的組標識號
getresuid 分別獲取真實的,有效的和保存過的用戶標識號
setresuid 分別設置真實的,有效的和保存過的用戶標識號
setfsgid 設置文件系統檢查時使用的組標識號
setfsuid 設置文件系統檢查時使用的用戶標識號
getgroups 獲取後補組標志清單
setgroups 設置後補組標志清單
八、進程間通信
ipc 進程間通信總控制調用
1、信號
sigaction 設置對指定信號的處理方法
sigprocmask 根據參數對信號集中的信號執行阻塞/解除阻塞等操作
sigpending 為指定的被阻塞信號設置隊列
sigsuspend 掛起進程等待特定信號
signal 參見signal
kill 向進程或進程組發信號
*sigblock 向被阻塞信號掩碼中添加信號,已被sigprocmask代替
*siggetmask 取得現有阻塞信號掩碼,已被sigprocmask代替
*sigsetmask 用給定信號掩碼替換現有阻塞信號掩碼,已被sigprocmask代替
*sigmask 將給定的信號轉化為掩碼,已被sigprocmask代替
*sigpause 作用同sigsuspend,已被sigsuspend代替
sigvec 為兼容BSD而設的信號處理函數,作用類似sigaction
ssetmask ANSI C的信號處理函數,作用類似sigaction
2、消息
msgctl 消息控制操作
msgget 獲取消息隊列
msgsnd 發消息
msgrcv 取消息
3、管道
pipe 創建管道
4、信號量
semctl 信號量控制
semget 獲取一組信號量
semop 信號量操作
5、共享內存
shmctl 控制共享內存
shmget 獲取共享內存
shmat 連接共享內存
shmdt 拆卸共享內存

Ⅲ 關於linux中ipcs -q 消息的問題

看了你的問題,做了個用例實驗了下,

發現 :msgget (0, IPC_CREAT) 和
msgget (0, 0) 的結果是一樣的,都是創建了一個新隊列.
這什麼意思? 這意思不就是說這兩個msgget創建不創建對象,不是IPC_CREAT說了算,而是它的第一個參數,此時值為0的key說了算? 看到這個,我頗感訝異.

然而,這訝異是我的誤會造成的。
cout了下IPC_PRIVATE的實際值,值為0.
查<<unix環境高級編程>>一書,書上說IPC_PRIVATE保證將創建一個新的IPC結構,也即新的IPC對象.
原文是: "The server can create a new IPC structure by specifying a key of IPC_PRIVATE and ....
The key IPC_PRIVATE guarantees that the server creates a new IPC structure. "
這解釋了,為什麼上面兩個msgget返回了兩個新id.

回到你的問題上來,顯然,使用msgget"通過key查id"只適用於msgget參數key不為0的情況.

Ⅳ Linux環境下 消息隊列編程 碰到些問題 msgsnd發送10個數據,msgrcv只能接受9個,第一個接受不到

0 -- hello
1 -- aaa
2 -- hello
3 -- hello
4 -- hello
5 -- hello
6 -- hello
7 -- hello
8 -- hello
9 -- end

不就是10個嗎

Ⅳ 如何將jpg或bmp轉換成mmap格式

開始---程序---附件---畫圖---文件---打開(打開你的圖片)---文件---另存為---保存類型---選你要的格式---保存。

閱讀全文

與linuxcmsgget相關的資料

熱點內容
58同城有人主動留微信 瀏覽:205
小米手機誤刪文件怎麼恢復 瀏覽:336
如何建立網站的平台 瀏覽:984
藍牙怎樣發文件在哪裡 瀏覽:780
tpc1061ti用什麼編程軟體 瀏覽:131
android中布局文件採用什麼格式 瀏覽:146
unity代碼修改了但是不編譯了 瀏覽:356
igs文件格式圖片 瀏覽:80
編程軟體為什麼不顯示中文 瀏覽:711
怎麼查看word文件版本 瀏覽:691
迷你編程怎麼讓樹葉變好看 瀏覽:310
qq親密號最低多少錢 瀏覽:917
電腦影像系統啟動文件導入出錯 瀏覽:908
word2007文檔刪除線 瀏覽:608
哪裡有自學的編程 瀏覽:432
榮耀手機哪些文件可以刪除垃圾 瀏覽:971
整人關機程序代碼 瀏覽:321
兩台linux傳文件 瀏覽:831
手機qq文件安全掃描失敗無法下載 瀏覽:378
linuxcmsgget 瀏覽:981

友情鏈接