Escolar Documentos
Profissional Documentos
Cultura Documentos
C 1 s bi tp nh sau:
1. Gi s c 1 chng trnh cn chy vi 1 so options nh -i, -1, -r, -f v sau -f s c 1
argument. Khi chng trnh chy nh sau:
$ ./argopt -i -lr 'hi there' -f fred.c -q
option: i
option: 1
option: r
option: f
filename: fred.c
argopt: invalid option q
unknown option: q
argument: hi there
{
int opt;
while((opt = getopt(argc, argv, "if:lr"))
switch(opt) {
case 'i ':
case '1 ':
case 'r ':
printf("option: %c\n", opt);
break;
1/44
!= -1) {
case 1f ':
printf("filename: %s\n", optarg);
break;
case ':':
printf ("option needs a value\n");
break;
case '? ':
printf("unknown option: %c\n", optopt);
break;
}
for(; optind < argc; optind++)
printf("argument: %s\n", argv[optind]);
return (0);
}
2. Hy vit chng trnh lm vic vi bin mi trng nh sau:
a. Lit k cc bin mi trng ca tin trnh hin ti thng qua bin ton cc
environ.
#include <stdlib.h>
#include <stdio.h>
int main()
{
char **env = environ;
while(*env) {
printf("%s\n",*env);
env++;
}
return (0);
}
b. Ly thng tin ca bin mi trng thng qua hm getenv. V d nh cc bin
PATH, HOME,...______________________________________
#include <stdlib.h>
iinclude <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
char *var, *value;
if (argc == 1 II argc > 3)
fprintf (stderr,"usage: environ var [value]\n");
exit (1);
>
var = argv[1];
value = getenv(var);
i f (value)
printf("Variable %s has value %s\n", var, value);
else
printf("Variable %s has no value\n", var);
i f (argc == 3) {
char *string;
value = argv[2];
2/44
string = malloc(strlen(var)+strlen(value)+2);
i f (string) {
fprintf(stderr,"out of memory\n");
exit (1);
}
strcpy(string,var);
strcat(string,"=");
strcat(string,value);
printf("Calling putenv with: %s\n",string);
i f (putenv(string) != 0) {
fprintf(stderr,"putenv failed\n");
free(string);
exit (1);
}
value = getenv(var);
i f (value)
printf("New value of %s is %s\n", var, value);
else
printf("New value of %s is null??\n", var);
}
return (0);
3/44
#include <sys/stat.h>
int stat(const char *restrict pathname, struct stat *restrict buf);
int fstat(int filedes, struct stat *buf);
struct stat {
m o d e t stm ode;
/* file type & mode (permissions) */
ino_t st ino;
/* i-node number (serial number) */
dev t st dev;
/* device number (file system) */
dev_t st rdev; /* device number for special files */
nlink t st_nlink; /* number of links */
uid_t st uid;
/* user ID of owner */
gid_t st gid;
/* group ID of owner */
off t stsize ;
/* size in bytes, for regular files *1
time t st atime; /* time of last access */
time_t stjmtime; /* time of last modification */
time_t st_ctime; /* time of last file status change */
blksize t st blksize; /* best I/O block size */
blkcnt_t st blocks; /* number of disk blocks allocated */
};
4/44
int
int
struct dirent
{
ino_t d ino;
/* i-node number */
char d_name[NAME_MAX + 1];
/* null-terminated filename */
}
DIR
*opendir(const char *pathname);
struct dirent *readdir(DIR *dp);
void
rewinddir(DIR *dp);
int
closcdir(DIR *dp);
long
telldir(DIR *dp);
void
seekdir(DIR *dp, long loc);
int
int
char
5/44
Vi cc hm nh vy chng ta c 1 s bi tp mu nh sau:
3. Vit chng trnh m phng cc lnh cp, rm, mv trong Unix (s dng cc li gi h
thng hoc cc hm th vin).
Lnh copy:
#include <stdio.h>
#define MAX_LINE_LEN 1000
void main(int argc, char* argv[])
{
char* file_path_from;
/* source path */
char* file_path_to;
/* target path */
FILE* f_from;
/* source stream */
FILE* f_to;
/* target stream */
char buf[MAX_LINE_LEN+1];
if (argc != 3 || !argv[l] || !argv[2]) {
fprintf(stderr, "Usage:
exit (1);
}
file_path_from = argv[l];
file_path_to = argv[2];
f_from = fopen(file_path_from, "r");
if (!f_from) {
fprintf(stderr, "Cannot open source file: ");
perror("");
exit (1);
}
f_to = fopen(file_path_to, "w+");
if (!f_from) {
fprintf(stderr, "Cannot open target file: ");
perror ("");
exit (1);
}
while (fgets(buf, MAX_LINE_LEN+1, f_from)) {
if (fputs(buf, f_to) == EOF) {
fprintf(stderr, "Error writing to target file:
perror("");
exit (1);
}
}
if (!feof(f_from)) {
fprintf(stderr, "Error reading from source file: ");
perror("");
exit (1);
}
if (fclose(f_from) == EOF) {
fprintf(stderr, "Error when closing source file: ");
perror ("");
}
if (fclose(f_to) == EOF) {
fprintf(stderr, "Error when closing target file: ") ;
perror("");
6/44
4. Xc nh thuc tnh ca cc file, m phng cng vic nh khi chy: $ Is -1 file name.
#include
#include
#include
#include
#include
#include
<ss/stat.h>
<stdio.h>
<time.h>
<io.h>
<sys/types.h>
<fcntl.h>
{
struct stat statbuf;
int stream;
char mode[20]="-rwxrwxrwx";
char output[200]
char temp[20]="";
if (argc==l)
{
printf("Usage: %s <file_n
return 1;
}
if ((stream = _open(argv[1', _0
{
perror("Error:");
return 1;
}
fstat(stream, Sstatbuf);
close(stream);
II Kiem tra quyen
if (!S_IRUSR(statbuf.st_mode) )
mode[1]='-';
if (!S_IWUSR(statbuf.st_mode) )
mode[ 2 ] ;
if (!S_IXUSR(statbuf.st_mode) )
mode[3]='-' ;
if (!S_IRGRP(statbuf.st_mode) )
mode[4]='-';
if (!S_IWGRP(statbuf.st_mode))
mode [ 5 ] =' - ' ;
if (!S_IXGRP(statbuf.st_mode))
mode[6]='-';
if (!S_IROTH(statbuf.st_mode) )
mode[7]='-';
if (!S_IWOTH(statbuf.st_mode))
mode[8]='-';
if (!S_IXOTH(statbuf.st_mode))
mode[9]='-';
// kiem tra loai file
if (S_ISLNK(statbuf.st_mode))
mode[0] = '1' ;
else if (S_ISCHR(statbuf.st_node) )
mode[0]='c ';
else if (S_ISBLK(statbuf.st_node))
mode[0]='b';
else if (S_ISSOCK(statbuf.stjnode))
mode[0]='s ';
else if (S_ISFIFO(statbuf.st_mode))
mode[0]='p';
strcat(output,mode); sprintf(temp," %s ", ctime(Sstatbuf.st_ctime));
strcat(output,temp); strcat(output," "); strcat(output,argv[0]); return
0;
7/44
}
5. M phng chng trnh thay i s hu hay quyn truy cp nh: chmod, chown, chgrp.
6. S dng cc hm dup, dup2 thay i hng vo ra d liu. V d khi thc hin hm
_____ printf th kt qu khng phi hin ra mn hnh m ghi vo file no ._________________
#include <ss/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int fd = open(argv[1]/ 0_CREAT I 0_WR0NLY);
//luu stdout
int oldstdout = dup(l);
//chuyen huong
dup2(fd, 1);
close(fd);
//in ra file tha vi stdout:
printf("test");
//khoi phuc stdout
dup2(oldstdout, 1);
close(oldstdout);
return 0;
<ss/stat.h>
<fcntl.h>
<unistd.h>
<ss/types.h>
<stdio.h>
{
int fd = open(argv[1], 0_RD0NLY);
struct stat statbuf;
char buf[256];
fstat(fd, Sstatbuf);
if (S_ISLNK(statbuf.st_mode) )
{
// doc ten file chua trong file lien ket mem nay
read(fd,buf,200);
close(fd);
fd = open(buf,0_RD0NLY);
printf("\n %s is symbolic link to %s", argv[1],buf);
}
while (read(fd,buf,256))
printf("%s",buf);
close(fd);
return 0;
2_______________________________________________________________________________________
<unistd.h>
<stdio.h>
<dirent.h>
<strinq.h>__________________________________________________________
8/44
#include <sys/stat.h>
void printdir(char *dir, int depth)
{
DIR *dp;
struct dirent *entry;
struct stat statbuf;
i f ((dp = opendir(dir)) == NULL) {
fprintf(stderr,"cannot open directory: %s\n", dir) ;
return;
}
chdir(dir);
while((entry = readdir(dp)) != NULL) {
stat(entry->d_name,&statbuf);
i f (S_ISDIR(statbuf.st_mode)) {
i f (strcmp(".",entry->d_name) == 0 ||
strcmp("..",entry->d_name) == 0)
continue;
printf("%*s%s/\n",depth,entry->d_name);
printdir(entry->d_name,depth+4);
}
else printf("%*s%s\n",depth,entry->d_name);
}
chdir("..");
closedir(dp);
}
int main()
{
printf("Directory scan of /home:\n");
printdir("/home",0);
printf("done.\n");
exit(0);
}
#include
#include
#include
#include
<sys\stat.h>
<fcntl.h>
<unistd.h>
<dirent.h>
{
static int depth = 0;
Dir *dp;
struct dirent *entry;
struct stat statbuf;
if ((dp= opendir(dir))==NULL)
{
perror("open:");
return;
}
chdir(dir);
// tang do sau
depth ++;
while ((entry= readdir(dp))!=NULL)
{
stat(entry->d_name,Sstatbuf);
______ if (S ISDIR(statbuf.st mode))
9/44
{
if ( (strcmp (".",entrv->_name)==0) II
strcmpC'. .", entry->d_name) ==0)
{
continue;
}
printf ("%s/\n",entry->d_name);
II neu dat do sau lon nhat thi dung de qui
if (depth < maxdepth)
{
printdir(entry->d_name,maxdepth);
}
}
else
{
// in ten file
printf("\t%s",entry->d_name);
}
}
closedir(dp);
>
int main(int argc,char *argv'])
{
if (argc < 3)
{
printf("\n Usage: %s <dir_name> <max_depth>",argvt0;);
return 1;
>
int maxdepth = atoi(argv[2]);
printdir(argv[1],maxdepth) ;
printf("\n done! \n") ;
return 0;
}
<stdio.h>
<unistd.h>
<string.h>
<malloc.h>
}
file_path = argv[l];
dir_path = (char*)malloc(strlen(file_path)+1);
if (!dir_path) {
_______ fprintf(stderr, "out of memory\n");______________________
10/44
exit (1);
}
p_slash = file_path;
while ( (p_slash = strchr(p_slash, '/')) != NULL) {
strncpy(dir_path, file_path, p_slash-file_path+l);
dir_path[p_slash-file_path+l] = '\0';
if (access(dir_path, F_OK) == -1) {
printf ("%s: Directory '%s' in the path does
not exist.\n","ACCESS DENIED", dir_path);
exit(2);
}
if (access(dir_path, X_OK) == -1) {
printf ("%s: Directory '%s' in the path - no 'X'
permission.\n","ACCESS DENIED", dir_path);
exit (2);
}
p_slash++;
}
tinclude <sys\stat.h>
#include <fcntl.h>
tinclude <unistd.h>
#include <io.h>
int main(int argc,char *argv[])
{
if (argc < 2)
{
printf(\n Usage: %s <file_name>",argv[0]);
return 1;
}
if (access(argv[1],F_0K)==-1)
{
printf("\n File doesnot exists");
return 1;
}
if (access(argv[1],R_OK)==0)
{
printf("\n file access OK");
return 0;
}
// tim thu muc cha hoac ong khong cho phep doc hoac thuc thi
char buf[100];
char *ptr;
char parent[100];
11/44
int reason=0;
int len=0;
struct stat statbuf;
//lay vi tri cuoi cung cua /
ptr = strrchr(argv[ 1 ;
len= ptr - argv[l];
//lay thu muc cha cua file argvfl]
strncpy(buf,argv[1], len) ;
//strcpy(parent,buf);
while (len !=0)
{
stat(buf,Sstatbuf);
if (! (statbuf.st_mode & S_IREAD) )
{
strcpy(parent,buf); //luu thu muc gay loi
reason = 0 ;
//khong C O quyen doc
}
else if (! (statbuf.st_mode & S_IEXEC))
{
strcpy(parent,buf); //luu thu muc gay loi
reason = 1;
//khong CO quyen thuc thi
}
ptr = strrchr(buf,'/');
len= ptr - buf;
//lay thu muc cha cua buf
strncpy(buf,buf,len);
>
if (reason)
{
printf("\n Thu muc %s khong CO quyen thuc thi",parent);
}
else
printf("\n Thu muc %s khong C O quyen doc",parent);
return 0;
}
10. Trong Unix, khi mun thc hin 1 file th h thng s xc nh s tn ti ca file trc.
S kim tra ph thuc vo ng dn ca file. C th l ng dn tuyt i, tng
i hoc ch l 1 tn file cn chy. Trng hp cui th h thng x thng qua bin PATH
xc nh xem file cn thc hin c nm mt trong cc ng dn trong PATH
khng. Hy vit chng trnh minh ha cng vic ny._____________________________
include
#include
#include
#include
#include
#include
<ss\stat.h>
<fcntl.h>
<unistd.h>
<io.h>
<stdlib.h>
<string.h>
12/44
retu rn 0;
}
II neu khong ton tai thi tim kiem trong bien moi truong PATH
buf = (char * ) malloc (256);
strcpy(buf, getenv("PATH"));
// chen them dau : vao cuoi buf cho de XU li
strcat(buf, " : ;
ptr = strchr(buf,':');
while (ptr!=NULL)
{
len = ptr - buf;
//lay path dau tien ke tu vi tri buf
strncpy(path,buf,len);
strcat(path,"/");
strcat(path,argv[1]);
if (access(path,F_OK)==0)
{
printf("\n File exists");
return 0;
}
II khong thay trong path thi tim tiep
buf = ptr;
ptr = strchr(buf,':');
}
// khong tim thay
printf("\n File not exists");
return 0;
J _______________________________________________________________________________________
13/44
11. To 1 tin trnh con bng hm FORK v xc nh cc thng tin ca tin trnh cha v tin
trnh con. (PID,PPID, UID, EUID, GID, EGID).
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
int main(int argc,char *argv'])
{
pid_t child_pid;
child_pid = Fork();
switch(child_pid)
{
case -1:
perrorC'Fork fail:");
return 1;
case 0: // tien trinh con
printf("\n child: %d %d %d %d %d %d",
getpid(),getppid{),getuid(),geteuid(), getgid() ,getegid() );
break;
default: // tien trinh cha
printf("\n parent: %d %d %d %d %d %d",
getpid 0 , getppid 0 , getuid 0 , geteuid 0 , getgid 0 , getegid 0);
>
return 0;
}__________________________ ____________________________________________________
//a
Int main()
{
Pid_t
pA, pB, pC,pD;
pB = fork(); // tach tien trinh B tu A
switch (pB)
{
Case -1: break;
Case 0: pC=fork();// sinh c tu B
Switch(pC)
{
Case -1 : break;
Case 0
: pD= fork();//sinh D tu c
Break;
Default : break;
I_____________________________________________
14/44
Default : break;
}
}
Int main()
{
Pid_t pA, pB,pC,pD;
pB=fork(); //sinh B tu A
switch (pB)
{
Case -1: break;
Case 0: break;
Default: pC=fork(); //sinh c tu A
pD= fork(); // sinh D tu A
}
Int main()
{
Pid_t
pl, p2a, p2b, p3a, p3b, p3c, p3d;
PI = fork() ; // sinh 1 tu 0
Switch(pl)
{
Case -1: break;
Case 0: p3d= fork();
//sinh3d tu 1
P2b= fork();
//sinh2b tu 1
If (p2b = = 0)
P3c =fork();
// sinh 3c tu 2b
Default : p3b = fork(); //sinh 3b tu 0
P2a = fork();
//sinh 2a tu 0
If (p2a = = 0)
p3a = fork.();
//sinh 3a tu 2a
}
}
13. Vit chng trinh m phng hm SYSTEM bng cch s dng cc hm FORK v
EXEC.
#include
finclude
#include
#include
<sys/types.h>
<unistd.h>
<stdio.h>
<sys/wait.h>
int main(){
pid_t child_id;
printf("Statrting process \n");
child_id=fork();
switch (child_id) {
case -1:
printf("fork error");
break;
case 0:
execlp("ps","ps","-af",0);
default:
wait (0) ;
printf("from parent: child finished \n");
_} ___________________________________________
15/44
re tu rn 0;
}
14. Vit chng nh minh ha cng vic chuyn hng vo ra. V d nh: c d liu t
___ file /etc/passwd sau sp xp cc hng theo ct tn ngi dng (ct th nht)._______
#include <unistd.h>
#inclue <stdio.h>
int main(int argc, char *argv[])
{
char *filename;
if (argc 1=2) {
fprintf(stderr, "usage: useupper file\n");
exit (1);
}
filename = argv[l];
i f (!freopen(filename, "r", stdin)) {
fprintf(stderr,
"could not redirect stdin to file %s\n", filename);
exit(2);
}
execlp("sort", "sort", "-0" , "-1" , 0) ;
fprintf(stderr, "could not exec sort!\n");
exit(3);
SIGNAL.
C ch lin lc thng qua Signal. Cc hm h thng sau c s dng:
#include <signal.h>
void (*signal(int sig, void (*func)(int)))(int);
#defme SIG_ERR (void (*)())-1 ; #define SIG DFL (void (*)()) 0;
#define SIG JG N (void (*)()) 1
int
kill(pid_t pid, int sig);
unsigned int alarm(unsigned int seconds);
int
pause(void);
in t
sigaction(int sig, const stru c t sigaction *act, struct sigaction *oact);
struct sigaction
{
void
(*sa_handler)(int);
/* addr of signal handler, */
sigset t sa mask;
I* additional signals to block */
int
sa flags;
/* signal options*/
void (*sa_sigaction)(int, siginfo t *, void *);
};
16/44
int
int
int
int
int
int
int
#include <stdio.h>
finclude <unistd.h>
finclude <signal.h>
int ctrl_c_count = 0;
#define
CTRL_C_MAX
17/44
printf("\nExiting...\n") ;
fflush(stdout);
exit (0);
}
else {
printf("\nContinuing\n");
fflush(stdout);
ctrl_c_count = 0;
}
}
sigprocmask(SIG_SETMASK, &old_set, NULL);
}
void catch_suspend(int sig_num)
{
sigset_t mask_set;
sigset_t old_set;
signal(SIGTSTP, catch_suspend);
sigfillset(&mask_set);
sigprocmask(SIG_SETMASK, &mask_set, &old_set);
printf("\n\nSo far, '%d'
Ctrl-C presses were counted\n\n", ctrl_c_count);
fflush(stdout);
sigprocmask(SIG_SETMASK, &old_set, NULL);
}
int main()
{
signal(SIGINT, catch_int);
signal(SIGTSTP, catch_suspend);
printf("Please random press Ctrl-C or Ctrl-Z");
while (1) {
sleep (1);
}
return 0;
}
18/44
unsigned int
sleep(unsigned int nsecs)
{
suspmask = odmask;
sigdelset(&suspmask, SIGALRM); /* make sure SIGALRM isn't blocked */
sigsuspend(&suspmask);
/* wait for any signal to be caught */
/* some signal has been caught, SIGALRM is now blocked */
unslept = alarm(O);
sigaction(SIGALRM, &oldact, NULL); /* reset previous action */
/* reset signal mask, which unblocks SIGALRM */
sigprocmask(SIG_SETMASK, &oldmask, NULL);
return (unslept);
}
PIPE v FIFO
s dng kt qu ca tin trnh ny l u vo ca tin trnh khc th ngoi ta dng PIPE hay
FIFO. Trong Unix c 1 s hm lm vic nh sau:
#incude <stdio.h>
FILE *popen(const char ^command, const char *open_mode);
int
pclose(FILE *stream_to_close);
Hm popen cho php tin trnh ang chy gi 1 chng trnh khc chy (sinh ra 1 tin trnh con)
sau s thc hin vic ly hoc truyn d liu cho tin trnh mi. Tin trnh mi c gi vi
tn chng trnh chy l const char *command. V d sau minh ha cho cch lm vic:
int man()
{
FILE *read_fp;
char buffer[BUFSIZ + 1];
int chars read;
meraset(buffer, '\0', sizeof(buffer));
read fp = popen("ps -ax", "r");
if (read fp != NULL)
{
buffer[chars_read - 1] = '\0';
printf("Reading:-\n %s\n", buffer);
chars read = fread(buffer, sizeof(char), BUFSIZ, read fp);
}
pclose(readfp);
exit(0);
}
exit(0);
}
int
int
int
key t
pipe(int file_descriptor[2]);
mkfifo(const char ^filename, mode_t mode);
mknod(const char *filename, mode t mode I S IFIFO, (dev t) 0);
ftok ( char *pathname, char proj );
close(data_pipe[1]);
while {(rc = read(data_pipet0], &c, 1)) > 0 )
putchar (c);
>
exit (0);
}
void do_parent(int data_pipe'])
{
int c;
____ int rc;_________________________________________________________________
20/44
close(data_pipe[0]);
while ((c = getcharO) > 0) {
rc = write(data_pipe]1], &c, 1) ;
if (rc == -1) {
perror("Parent: pipe write error");
close(data_pipe[1]) ;
exit(1);
}
}
close(data_pipe[1]);
exit (0);
}
int main()
{
int data_pipe[2];
int pid;
int rc;
rc = pipe(data_pipe);
if (rc == -1) {
perror("pipe create error ");
exit (1);
}
pid = fork();
switch (pid) {
case -1:
perror("fork error");
exit (1);
case 0:
do_child(data_pipe) ;
default:
do_parent(data_pipe) ;
}
return 0;
}
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
int main(int argc,char *argv]])
{
int pipes[2];
int pid;
char buf[100];
if (pipe(pipes) == -1)
{
perror("error:");
return 1;
}
//chuyen huong nhap xuat
dup2(pipes[0],STDIN_FILENO);
close (pipes[0]);
dup2(pipes[1],STDOUT_FILENO) ;
close(pipes[0]);
21/44
pi= fork();
switch(pid)
{
case -1:
perror("fork error:");
return 1;
case 0:
II child ch? d?c ->dng d?u ghi
close (1);
IIghi ra stderr d? hi?n ra mn hnh
gets(buf);
fprintf(stderr,"%s",buf) ;
break;
default:
// parent ch? ghi -> dng d?u d?c:
close (0) ;
printf("from parent: test");
}
return 0;
}
<unistd.h>
<stdlib.h>
<stdio.h>
<string.h>
<fcntl.h>
<limits.h>
<ss/tpes.h>
<sys/stat.h>
exit(EXIT_FAILURE) ;
}
}
printf("Process %d opening FIFO 0_WR0NLY\n",
g
etpid()) ;____________________________________________________________________
22/44
'\0', sizeof(buffer));
P r o g A .c
23/44
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#define FIFO_NAME "/tmp/testfifo"
int main(int argc,char *argv]])
{
int fd;
if (access(FIF0_NAME,F_0K)==-1)
if (mkfifo(FIFO_NAME,0777) != 0 )
{
perror("make fifo:");
return 1;
}
fd = open(FIFO_NAME,0_WR0NLY) ;
if (fd != -1)
{
write(fd, "hello",PIPE_BUF);
close(fd);
}
return 0;
}
ProgB.c
include <unistd.h>
include <stdio.h>
include <signal.h>
define FIFO_NAME "/tmp/testfifo"
int main(int argc,char *argv[])
{
int fd;
char buf[PIPE_BUF+1]
fd = open(FIF0_NAME,0_WR0NLY) ;
if (fd != -1)
{
read(fd,buf,PIPE_BUF);
printf("receive: %s",buf);
close(fd);
}
else
{
fprintf(stderr,"pipe not exist");
return 1;
}
return 0;
Message Queues
24/44
int
int
int
int
struct msqid ds
{
struct ipc_perm
{
__k e y t __key;
_uid t uid;
__gid_t gid;
__uid t cuid;
gid t cgid;
unsigned short int mode;
/* Key
*/
/* Owner's user ID. */
/* Owner's group ID. */
/* Creator's user ID. */
/* Creator's group ID. */
/* Access permission. */
};
struct msgbuf
{
<stdio.h>
<stdlib.h>
<ss/tpes-h>
<ss/ipc.h>
<sys/msg.h>
25/44
0777);
if (queue_id == -1) {
perror("main: msgget error");
exit (1);
}
printf("message queue created, queue id '%d'.\n",
queue_id);
msg = (struct msgbuf*)malloc(sizeof(
struct
msgbuf)+MAX_MSG_SIZE);
for (i=l; i <= NUM_MESSAGES; i++) {
msg->mtype = (i % 3) + 1;
sprintf(msg->mtext, "hello world - %d", i) ;
rc = msgsnd(queue_id, msg, strlen(msg->mtext)+1, 0);
if (rc == -1) {
perror("main: msgsnd error");
exit (1);
}
}
free(msg);
printf("generated %d messages, exiting.\n",
NU
M_MESSAGES);
return 0;
}
include
include
include
include
include
include
<stdio.h>
<stdlib.h>
<unistd.h>
<sys/types.h>
<sys/ipc.h>
<sys/msg.h>
include "queue_defs.h"
struct msgbuf{
long int mtype;
char mtext[1];
};
26/44
3 .\n") ;
exit (1);
}
msg_type = atoi(argv[1]);
if (msg_type < 1 || msg_type > 3 ) {
fprintf(stderr, "Usage: %s <message type>\n",
argv[0]);
fprintf(stderr,
and 3.\n");
exit (1) ;
}
queue_id = msgget(QUEUE_ID, 0);
if (queue_id == -1) {
perror("main: msgget error") ;
exit(1);
}
printf("message queue opened, queue id '%d'.\n",
queue_id);
msg = (struct msgbuf*)malloc(sizeof(
struct msgbuf)+MAX_MSG_SIZE) ;
while (1) {
rc = msgrcv(queue_id, msg, MAX_MSG_SIZE+1,
ms
g_type, 0);
if (rc == -1) {
perror("main: msgrcv error");
exit (1);
}
printf("Reader '%d' read message: '%s'\n",
msg_type, msg>mtext);
sleep (1);
}
return 0;
ProgA.c
include <unistd.h>
include <stdio.h>
include <signal.h>
27/44
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdlib.h>
#define MSGQID 1234
#define MAX_LEN 256
struct msgbuf
{
long mtype;
char mtext[1];
} *msg;
int main(int argc,char *argv^])
{
int qid;
int ret;
qid = msgget(MSGQID, IPC_CREAT | 0777);
if (qid == -1)
{
perror("msgget error:");
return 1;
}
msg = (struct msgbuf *) malloc(sizeof(struct msgbuf) + MAX_LEN);
msg->mtype=0;
strcpy(msg->mtext,"From Process A");
ret = msgsnd(qid, msg, strlen(msg->mtext)+1,0);
if (ret == -1)
{
perror("msgsnd error:");
return 1;
}
return 0;
ProgB.c
#include
#include
include
include
include
include
<unistd.h>
<stdio.h>
<signal.h>
<sys/ipc.h>
<sys/msg.h>
<stdlib.h>
28/44
perror{"msgget error:");
return 1;
}
msg = (struct msgbuf *) malloc(sizeof(struct msgbuf) + MAX_LEN);
ret = msgrcv(qid, msg, MAX_LEN + 1,0,0);
if (ret == -1)
{
perror("msgsnd error:");
return 1;
}
printf("Process B received: %s",msgbuf->mtext);
return 0;
}
Tested by HCricket
/'/ProA.c
include
include
include
include
include
<sys/types.h>
<sys/ipc.h>
<sys/msg.h>
<stdio.h>
<string.h>
define MSGSZ
128
/*
* Declare the message structure.
*/
-ypedef struct msgbuf {
long
mtype;
char
mtext[MSGSZ];
} message_buf;
main ()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
message_buf sbuf;
size_t buf_length;
/*
* Get the message queue id for the
* "name" 1234, which was created by
* the server.
*/
key = 1234;
(void) fprintf(stderr, "\nmsgget: Calling msgget(%^lx,\
%#o)\n",
key, msgflg);
if ((msqid = msgget(key, msgflg )) < 0) {
perror("msgget");
exit (1);
}
else
(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);
29/44
/*
* We'll send message type 1
*/
sbuf.mtype = 1;
(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);
(void) strcpy(sbuf.mtext, "Did you get this?");
(void) fprintf(stderr,"msgget: msgget succeeded: msqid = %d\n", msqid);
buf_length = strlen(sbuf.mtext) + 1 ;
/*
* Send a message.
*/
if (msgsnd(msqid, Ssbuf, buf_length, IPC_NOWAIT) < 0) {
printf ("%d, %d, %s, %d\n", msqid, sbuf.mtype, sbuf.mtext, buf_length);
perror("msgsnd");
exit (1);
}
else
printf("Message: \"%s\" Sent\n", sbuf.mtext);
exit (0);
}
//ProB.c
include
include
include
include
<sys/types.h>
<sys/ipc.h>
<sys/msg.h>
<stdio.h>
define MSGSZ
128
,/*
* Declare the message structure.
*/
typedef struct msgbuf {
long
mtype;
char
mtext[MSGSZ];
} message_buf;
main ()
{
int msqid;
key_t key;
message_buf
rbuf;
/*
* Get the message queue id for the
* "name" 1234, which was created by
* the server.
*/
key = 1234;
30/44
/*
* Receive an answer of message type 1.
*/
if (msgrcv(msqid, Srbuf, MSGSZ, 1, 0) < 0) {
perror("msgrcv");
exit(1);
}
/*
* Print the answer.
*/
printf("%s\n", rbuf.mtext);
exit (0);
Shared Memory
void
int
int
int
stru ct shm id ds
{
<stdio.h>
<sys/tpes.h>
<sys/ipc.h>
<ss/shm.h>
31/44
struct country {
char name[30];
char capital_city[30];
char currency[30];
int population;
int main()
{
int shm_id;
char* shm_addr;
int* countries_num;
int* stop;
include <stdio.h>
include <sys/types.h>
include <sys/ipc.h>
include <sys/shm.h>
struct country {
char name[30];
____ char capital city[30];
32/44
char currency[30];
int population;
};
int main()
{
int shm_id;
char* shm_addr;
int* countries_num;
:nt* stop;
33/44
<unistd.h>
<stdio.h>
<sys/ipc.h>
<sys/shm.h>
P r o g B .c
34/44
0777);
include <unistd.h>
include <stdio.h>
include <sys/ipc.h>
include <sys/shm.h>
define SHMID 1234
define MAX LEN 256
0777);
II attach
shm_addr = shmat(id , NULL , 0) ;
if ( !shm_addr )
{
perror("shmat error:");
return 1;
}
// doc du lieu tu vung nho chung
size = (int *)shm_addr;
strncpy(msg, shm_addr + sizeof(int) , *size);
printf("Process B received: %s", msg);
//detach
ret = shmdt(shm_addr);
if (ret == -1)
{
perror("shmdt error:");
return 1;
}
return 0;
}____________________________________________
35/44
Tested by HouseCricket
ProgA.c
include
include
include
include
<sys/types.h>
<sys/ipc.h>
<sys/shm.h>
<stdio.h>
define SHMSZ
27
main ()
{
char c;
int shmid;
key_t key;
char *shm, *s;
/*
* We'll name our shared memory segment
* "5678".
*/
key = 567 8;
/*
* Create the segment.
*/
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit (1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit (1);
}
/*
* Now put some things in~o the memory for the
* other process to read.
*/
s = shm;
for (c = 'a'; c <= z'; C++)
*s++ = c;
*s = NULL;
/*
*
*
*
*
*/
while (*shm != '*')
sleep(1);
exit (0);
//ProgB.c
37/44
Semaphores
#include <sys/sem.h>
int
int
int
<stdio.h>
<sys/types-h>
<ss/ipc.h>
<sys/shm.h>
<ss/sem.h>
<wait.h>
<time.h>
<stdlib.h>
define SEM_ID
include <unistd.h>
250
union semun {
int val;
struct semid_ds *buf;
unsigned short int *array;
};
struct country {
char name[30];
char capital_city[30];
char currency[30];
int population;
};
void
{
random_delay()
static int initialized = 0;
int random_num;
struct timespec delay;
if (initialized) {
srand(time(NULL) );
initialized = 1;
}
random_num = rand() % 10;
delay.tv_sec = 0;
delay.tv_nsec = 10*randon_num;
nanosleep(Sdelay, NULL);
}
void
38/44
{
struct sembuf sem_op;
sem_op.sem_num = 0;
sem_op.sem_op = -1;
sem_op.sem_flg = 0;
semop(sem_set_id, &sem_op, 1) ;
}
void
{
sem_unlock(int sem_set_id)
struct sembuf sem_op;
sem_op.sem_num = 0;
sem_op.sem_op = 1;
sem_op.sem_flg = 0;
semop(sem_set_id, &sem_op, 1);
}
void
{
sem_lock(sem_set_id);
strcpy(countries[*countr:es_num].name,
country_name);
strcpy (countries [*countnes_num] .capital_city,
capital_city);
strcpy (countries [*countnes_num] .currency,
currency);
countries [*countries_nurrf .population = population;
(*countries_num)++;
sem_unlock(sem_set_id) ;
}
void
{
add_country(sem_set_id, countries_num, counties,
"U.S.A", "Washington",
"U.S. Dollar", 250000000);
random_delay();
add_country(sem_set_id, countries_num, counties,
"Israel", "Jerusalem",
"New Israeli Shekel", 6000000);
random_delay();
add_country(sem_set_id, countries_num, counties,
"France", "Paris",
"Frank", 60000000);
39/44
random_delay();
add_country(sem_set_id, countries_num, counties,
"Great Britain", "London",
"Pound", 55000000);
}
void do_parent(int sem_set_id, int* countries_num,
struct country* countries)
{
int i, num_loops;
for (num_loops=0; num_loops < 5; num_loops++)
sem_lock(sem_set_id);
printf ("------------------------------- \n");
printf("Number Of Countries: %d\n",
*countries_num);
for (i=0; i < (*countries_num); i++) {
printf("Country %d:\n", i+1);
printf(" name: %s:\n", countries[i].name);
printf (" capital city: %s:\n",
countries[i].capital_city);
printf(" currency: %s:\n",
countries[i].currency);
printf (" population: %d:\n",
countries[i].population);
}
sem_unlock(sem_set_id) ;
random_delay();
}
}
int main()
{
int sem_set_id;
union semun sem_val;
int shm_id;
char* shm_addr;
int* countries_num;
struct country* countries;
struct shmid_ds shm_desc;
int rc;
pid_t pid;
sem_set_id = semget(SEM_ID, 1, IPC_CREAT | 0777);
if (sem_set_id == -1) {
perror("main: semget");
exit (1);
}
sem_val.val = 1;
rc = semctl(sem_set_id, 0, SETVAL, sem_val);
if (rc == -1) {
perror("main: semctl");
exit (1);
40/44
}
shm id = shmget(100, 2048,
IPC_CREAT | IPC_EXCL
if (shm id == -1) {
perror("main: shmget error");
exit (1);
}
shm addr = shmat(shm id, NULL, 0);
if (!shm addr) {
perror("main: shmat error ");
exit (1);
}
countries num = (int*) shm addr;
*countries num = 0;
countries = (struct country*)
((void*)shm addr+sizeof(int));
pid = fork();
switch (pid) {
case -1:
perror("fork error ");
exit (In
break;
case 0:
do child(sem set id, countries num, countries);
exit (0);
break;
default:
do parent (sem set id, countries num, countries);
break;
}
{
int child status;
wait(&child status);
}
if (shmdt(shm addr) == -1) {
perror("main: shmdt error ");
}
if (shmctl(shm id, IPC RMID, &shm desc) == -1) {
perror("main: shmctl error ");
}
return 0;
}
P r o g A .c
include
include
include
include
include
<unistd.h>
<stdio.h>
<sys/ipc.h>
<sys/shm.h>
<sys/sem.h>
41/44
0600);
0777);
ProgB.c
include
include
include
include
include
<unistd.h>
<stdio.h>
<sys/ipc.h>
<sys/shm.h>
<sys/sem.h>
42/44
43/44
Tested by Housecricket
.//ProA. c
include
include
include
include
include
define
define
define
define
<stdio.h>
<string.h>
<sys/ipc.h>
<sys/sem.h>
<sys/shm.h>
SEMKEYPATH "/dev/null"
SEMKEYID 1
SHMKEYPATH "/dev/null"
SHMKEYID 1
/*
/*
/*
/*
*/
*/
*/
*/
define NUMSEMS 2
define SIZEOFSHMSEG 50
*/
*/
define NUMMSG 2
*/
*/
and*/
*/
}
/*
/*
/*
/*
{
printf("main: semget (| failed\n");
return -1;
}
/*
/*
I*
/*
/*
/*
/*
/*
/*
/*
/*
sarray[0] = 0;
sarray[1] = 0;
44/44
*/
*/
I
*/
*/
*/
*/
*/
*/
*/
*/