Common API s for embedded software application layer development

Posted by irish21 on Sat, 22 Jan 2022 06:00:11 +0100

Standard IO and file IO

1.fopen open flow

FILE *fopen(const char *path, const char *mode);
This function can be used to open a standard IO stream. The stream pointer is returned on success and NULL on error. A total of 1021 streams can be opened except stdin, stdout and stderr (standard input, standard output and standard error).
Path: the path of the file to open
mode:
Usage example:

#include <stdio.h>

int main(int argc, const char *argv[])
{
	FILE *fp;
//	fp = fopen("1.txt", "r");
//	fp = fopen("1.txt", "r+");
	fp = fopen("1.txt", "w");
//	fp = fopen("1.txt", "w+");
//	fp = fopen("1.txt", "a");
//	fp = fopen("1.txt", "a+");
	printf("fp = %x\n", (int)fp);
	return 0;
}

2.perror error handling

void perror(const char *str);
Output a descriptive error message to the standard error stderr.
str: customized prompt error message
Usage example:

#include <stdio.h>

int main ()
{
  FILE *fp;

  /* Rename the file first */
  rename("file.txt", "newfile.txt");

  /* Now let's try to open the same file */
  fp = fopen("file.txt", "r");
  if( fp == NULL ) {
     perror("Error");
     return(-1);
  }
  fclose(fp);
     
  return(0);
}
//Error: No such file or directory

3.strerror error handling

extern int errno;
char *strerror(int errno);
Return the corresponding error information according to the error number.

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(int argc, const char *argv[])
{
	FILE *fp;
	fp = fopen("1.txt", "r");
	printf("%s\n", strerror(errno));
	printf("fp = %x\n", (int)fp);
	return 0;
}
//No such file or directory

4.fclose close flow

int fclose(FILE *stream);
Close the flow. After the flow operation (opening, reading and writing), close the flow at last.

5.fgetc input by character


Usage example:

#include <stdio.h>

int main(int argc, const char *argv[])
{

/*	char ch;
	ch = fgetc(stdin);
	printf("read:%c\n", ch);
*/
	FILE *fp = fopen("1.txt", "r");
	if (fp != NULL)
		printf("read:%c\n", fgetc(fp));
	else
		perror("fopen");
	return 0;
}
//read:a

6.fputc output by character


Usage example:

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(int argc, const char *argv[])
{
	FILE *fp = fopen("1.txt", "a");
	if (fp != NULL)
	//Write x to the stream file represented by fp
		printf("write:%c\n", fputc('x', fp));
	else
		printf("%s\n", strerror(errno));
	return 0;
}

7.fgets enter by line


Usage example:
ABCD ABCD (because the last one is \ 0)

8.fputs output by line


Usage example:

#include <stdio.h>

int main(int argc, const char *argv[])
{
	char ch[5];
	fgets(ch, 5, stdin);
//	puts(ch);
	fputs(ch, stdout);
	return 0;
}

9. Input and output of FREAD and fwrite objects


Usage example:

#include <stdio.h>
#include <string.h>

typedef struct
{
	char name[16];
	int no;
	char sex[8];
}Student;

int main(int argc, const char *argv[])
{
	FILE *fp;
	fp = fopen("1.txt", "w+");
	if (fp == NULL)
		return -1;
	Student stu;
	strcpy(stu.name, "zhangsan");
	stu.no = 10;
	strcpy(stu.sex, "male");
	int fw = fwrite(&stu, sizeof(stu), 1, fp);
	if (fw >0)
	{
		fread(&stu, sizeof(stu), 1, fp);
		printf("name:%s, no:%d, sex:%s\n", stu.name, stu.no, stu.sex);
	}
	fclose(fp);
	return 0;
}

10.fflush brush new flow


Instead of waiting for the data in the buffer, the data in the stream buffer is directly written to the actual file.
Usage example:

#include <stdio.h>

int main(int argc, const char *argv[])
{
	int i;
	for (i = 0; i < 100; i++)
	{
		printf("a");
	}
	fflush(stdout);
	while(1);
	return 0;
}

In general, the buffer is released only when a newline character or return is encountered.

11.ftell, fseek, rewind location flow


Usage example:

#include <stdio.h>

int main(int argc, const char *argv[])
{
	FILE *fp = fopen("2.txt", "a+");
	if (fp == NULL)
	{
		perror("fopen");
		return -1;
	}
	printf("ftell:%ld\n", ftell(fp));
	fputs("xxx", fp);
	printf("ftell:%ld\n", ftell(fp));
	fseek(fp, 0, SEEK_SET);
    //rewind(fp); Navigate to file header
	char ch[5];
	fgets(ch, 4, fp);
	printf("read:%s\n", ch);
	return 0;
}

12.ferror and feof judge whether the flow is wrong or ended

13.printf, sprintf, fprintf formatted output


printf is spliced and output to standard output, fprintf is spliced and output to the stream file represented by stream, and sprintf is spliced and output to the string represented by s
Usage example:

#include <stdio.h>

int main(int argc, const char *argv[])
{
	int year = 2021;
	int mon = 5;
	int day = 25;
	FILE *fp = fopen("2.txt", "w");
	if (fp)
	{
		fprintf(fp, "%04d-%02d-%02d\n", year, mon, day);
	}
	char ch[16];
	sprintf(ch, "%04d-%02d-%02d\n", year, mon, day);
	puts(ch);
	return 0;
}
//2. There will be date content in txt and date content in string ch

14.fscanf, sscanf format input

15.open file


Usage example:

16.close close file


After the file IO is completed, close the file with close.

17.read file


Usage example:

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

int main(int argc, const char *argv[])
{
	int fd;
	int n = 0;
	char buf[5];
	fd = open("1.txt", O_RDONLY);
	if (fd)
	{
		while (read(fd, buf, 1) > 0)
		{
			n++;
		}
		printf("n = %d\n", n);
	}
	else
		perror("open");
	return 0;
}
//Calculate file size

18.write file


Usage example:

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

int main(int argc, const char *argv[])
{
	int fd;
	fd = open("1.txt", O_WRONLY | O_CREAT, 00666);
	char buf[10];
	if (fd)
	{
		fgets(buf, 8, stdin);
		write(fd, buf, 8);
	}
	return 0;
}
//Enter a line from the keyboard and write it to the file

19.lseek location file

20.opendir Open Directory


name: file directory to open
Usage example:

int main()
{
	DIR *dir;
	dir = open(".");
	if(dir)//if dir != NULL opened successfully
	{
		...
	}
	return 0;
}

21.readdir reads the contents of the directory stream

Usage example:

#include <stdio.h>
#include <dirent.h>

int main(int argc, const char *argv[])
{
	DIR *dir;
	struct dirent *dent;
	dir = opendir(".");
	if (dir)
	{
		while ((dent = readdir(dir)) != NULL)
		{
			printf("%s\n", dent->d_name);
		}
	}
	return 0;
}
//Read all file names in the directory

22.closedir close directory file

23.chmod and fchmod modify file access permissions

24.stat, lstat, fstat get file attributes

Usage example:

#include <stdio.h>
#include <dirent.h>
#include <sys/stat.h>

int main(int argc, const char *argv[])
{
	DIR *dir;
	struct dirent *dent;
	struct stat buf;
	dir = opendir(".");
	if (dir)
	{
		while ((dent = readdir(dir)) != NULL)
		{
			stat(dent->d_name, &buf);
			printf("%s, %d\n", dent->d_name, (int)buf.st_size);
		}
	}
	return 0;
}
//Print all files in the directory and their sizes

Processes and threads

1.fork creation process


Usage example:

2. End of exit process

3.wait process recovery


Usage example:

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

int main(int argc, const char *argv[])
{
	pid_t pid;
	pid = fork();
	if (pid > 0)
	{
		printf("this is father fork\n");
		wait(NULL);
		printf("child fork is dead\n");
		while(1);
	}
	else if (pid == 0)
	{
		printf("this is child fork\n");
	}
	else
	{
		perror("fork");
		return -1;
	}
	return 0;
}
//Recycle child process

Usage example 2:

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

int main(int argc, const char *argv[])
{
	pid_t pid;
	int status;
	pid = fork();
	if (pid > 0)
	{
		printf("this is father fork\n");
		wait(&status);
		printf("child fork is dead, ret = %d\n", WEXITSTATUS(status));
		while(1);
	}
	else if (pid == 0)
	{
		printf("this is child fork\n");
		exit(10);
	}
	else
	{
		perror("fork");
		return -1;
	}
	return 0;
}

4.waitpid reclaims the specified child process


Usage example:

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

int main(int argc, const char *argv[])
{
	pid_t pid;
	int status;
	pid = fork();
	if (pid > 0)
	{
		printf("this is father fork\n");
//		wait(&status);
		waitpid(pid, &status, 0);
		printf("child fork is dead, ret = %d\n", WEXITSTATUS(status));
		while(1);
	}
	else if (pid == 0)
	{
		printf("this is child fork\n");
		exit(10);
	}
	else
	{
		perror("fork");
		return -1;
	}
	return 0;
}

5.exec function family

The exec function family is used to execute a program

execlp(path) looks for the file name from the environment variable
execl can only write absolute paths
Usage example:

After using execlp, you can find files from environment variables, so you can directly use ls:
printf cannot be printed because execl function will replace the following code:

Compared with execl and execlp functions:
execv and execvp functions can execute code by passing parameters, which is more flexible
Usage example:

6. Encapsulation of exec function by system


Usage example:
In the source code, the system function uses the sub process to execute the exec function family. The code will not be replaced. You can continue to execute subsequent programs

7.pthread_create create thread, pthread_self view your tid

Usage example:

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void *func1(void *arg)
{
	printf("this is func1\n");
}
void *func2(void *arg)
{
	printf("this is func2\n");
	exit(0);
}
int main(int argc, const char *argv[])
{
	pthread_t th1, th2;
	int err;
	err = pthread_create(&th1, NULL, func1, NULL);
	if (err != 0)
	{
		printf("pthread_create:%s\n", strerror(err));
		return -1;
	}
	err = pthread_create(&th2, NULL, func2, NULL);
	if (err != 0)
	{
		printf("pthread_create:%s\n", strerror(err));
		return -1;
	}
	sleep(1);
	printf("this is main thread\n");
	return 0;
}

8.pthread_join recycle thread

Just like the child process exits and the parent process is not recycled, the child process will become a zombie process,
If the thread is not recycled, it will still occupy resources

Usage example:

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void *func(void *arg)
{
	printf("this is func\n");
	sleep(20);
	printf("finish\n");
}

int main(int argc, const char *argv[])
{
	pthread_t tid[100];
	int err;
	int i;
	for (i = 0; i < 100; i++)
	{
		err = pthread_create(&tid[i], NULL, func, NULL);
		if (err != 0)
		{
			printf("pthread_create:%s\n", strerror(err));
			return -1;
		}
	}
	for (i = 0; i < 100; i++)
	{
		err = pthread_join(tid[i], NULL);
		if (err != 0)
		{
			printf("pthread_join:%s\n", strerror(err));
			return -1;
		}
	}
	sleep(20);
	return 0;
}

View the running thread by ps -eLf | grep program name
View the resources occupied by the process through the top -p process number
Found that pthread was used_ After the join reclaims threads, the resource occupancy rate is significantly reduced

9.pthread_exit ends the current thread


Usage example:

#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void *func(void *arg)
{
	printf("this is func\n");
	sleep(2);
	pthread_exit("func finish\n");
}

int main(int argc, const char *argv[])
{
	pthread_t tid;
	int err;
	int i;
	err = pthread_create(&tid, NULL, func, NULL);
	if (err != 0)
	{
		printf("pthread_create:%s\n", strerror(err));
		return -1;
	}
	void *retval;
	pthread_join(tid, &retval);
	printf("retval = %s\n", (char *)retval);
	sleep(2);
	return 0;
}

10.pthread_detach thread auto recycle

Add the detach attribute to the thread to allow it to automatically recycle resources after executing the callback function after creation without pthread_exit and pthread_join.
int pthread_detach(pthread_t thread);
Usage example:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

#define NUM 100

void *func(void *arg)
{
	printf("this is func,%d\n", (int)arg);
	sleep(20);
}

int main(int argc, const char *argv[])
{
	int i, err;
	pthread_t tid[NUM];
	for (i = 0; i < NUM; i++)
	{
		err = pthread_create(&tid[i], NULL, func, (void *)i);
		if (err != 0)
		{
			printf("pthread_create:%s\n", strerror(err));
			return -1;
		}
		pthread_detach(tid[i]);
	}
	while(1)
		sleep(1);
	return 0;
}

11.pthread_cancel cancel thread


What is called canceling a thread: it is to stop the running thread
Call pthread_ After canceling, there are three ways to cancel the thread:

  1. There are cancel points (blocking functions), such as sleep(),read(),write()
  2. Manually set the cancel point and call pthread_testcancel();
  3. Use asynchrony, setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

If a property that cannot be cancelled is set, the thread cannot be cancelled:
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);

Usage example:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void *funct(void* arg){
	int a=0;
    a = (int)arg;
	int td = pthread_self();
	pthread_detach(pthread_self());

	printf("this is thread a=%d\n",a);
	//pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
	while(1){
		sleep(1);
		//pthread_testcancel();
	}
		
	
}

int main(){
	
	int re,i=0;
	pthread_t tid;
	
	re = pthread_create(&tid, NULL,funct, (void *)i);
	pthread_detach(tid);
	if(re!=0){
		printf("pthread_create:%s\n",strerror(re));
		exit(0);
	}
	//Cancel the thread 5 seconds after the thread is created
	sleep(5);
	
	pthread_cancel(tid);
	


	while(1){
		sleep(1);
	}

}

12.sem_init,sem_wait,sem_ Thread synchronization mechanism based on post semaphore

Thread synchronization mechanism: let threads run in order.
P(sem_wait()): consuming resources, waiting resources, semaphore - 1
V(sem_post()): production resource, release resource, semaphore + 1

Usage example:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>

char buffer[100];
sem_t sem;

void *write(void* arg){
	int a=0;
    a = (int)arg;
	int td = pthread_self();
	pthread_detach(pthread_self());
	while(1){
		fgets(buffer,20,stdin);
		sem_post(&sem);  //Write thread, release resources after writing, and use V operation function sem_post
	}
}

void *read(void* arg){
	int a=0;
    a = (int)arg;
	int td = pthread_self();
	pthread_detach(pthread_self());

	while(1){
		memset(buffer,0,100);
		sem_wait(&sem);   //The read thread waits for the resources of the write thread, and uses the P operation function sem_wait
		
		printf("%s\n",buffer);

	}

}

int main(){
	
	int re,i=0;
	pthread_t tid1,tid2;
	//Initialization semaphore
	sem_init(&sem,0,0);
	
	re = pthread_create(&tid1, NULL,read, (void *)i);
	pthread_detach(tid1);
	if(re!=0){
		printf("pthread_create:%s\n",strerror(re));
		exit(0);
	}
	re = pthread_create(&tid2, NULL,write, (void *)i);
	pthread_detach(tid2);
	if(re!=0){
		printf("pthread_create:%s\n",strerror(re));
		exit(0);
	}	


	while(1){
		sleep(1);
	}

}
//The synchronization mechanism of write before read is guaranteed

13.pthread_mutex_init,pthread_mutex_lock,pthread_mutex_unlock mutex lock implements the mutex mechanism between threads

Mutual exclusion mechanism: only one process or thread is allowed to access critical resources between processes and threads.
Critical resources: shared resources, such as the same file to be written by multiple threads
Mutex mutex: the task applies for a lock before accessing critical resources, and releases the lock after accessing.

Usage example:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>

FILE *fp;

pthread_mutex_t mutex;

void *write1(void* arg){
	int a=0;
    a = (int)arg;
	int len,i;
	char *c1 = "Hello world\n";
	char *c2;
	len = strlen(c1);
	int td = pthread_self();
	pthread_detach(pthread_self());
	c2 = c1;
	while(1){
	   //Apply for locks for critical resources
	   pthread_mutex_lock(&mutex);
	   for(i=0;i<len;i++){
		  fputc(*c1,fp);
		  fflush(fp);
		  c1++;
		  usleep(10000);
	   }
	   //Release locks for critical resources
	   pthread_mutex_unlock(&mutex);
	   c1 = c2;
	   sleep(1);
	}
}

void *write2(void* arg){
	int a=0;
    a = (int)arg;
	int len,i;
	char *c1 = "How are your\n";
	char *c2;
	c2 = c1;
	len = strlen(c1);
	int td = pthread_self();
	pthread_detach(pthread_self());
	while(1){
	   //Apply for locks for critical resources
	   pthread_mutex_lock(&mutex);	
	   for(i=0;i<len;i++){
		  fputc(*c1,fp);
		  fflush(fp);
		  c1++;
		  usleep(10000);
	   }
	   //Release locks for critical resources
	   pthread_mutex_unlock(&mutex);
	   c1 = c2;
	   sleep(1);	
	}

}

int main(){
	
	int re,i=0;
	pthread_t tid1,tid2;
	
	fp = fopen("1.txt","w");
	if(!fp){
		perror("fopen");
		return -1;
	}
	//Initialization lock
	pthread_mutex_init(&mutex,NULL);
	
	re = pthread_create(&tid1, NULL,write1, (void *)i);
	pthread_detach(tid1);
	if(re!=0){
		printf("pthread_create:%s\n",strerror(re));
		exit(0);
	}
	re = pthread_create(&tid2, NULL,write2, (void *)i);
	pthread_detach(tid2);
	if(re!=0){
		printf("pthread_create:%s\n",strerror(re));
		exit(0);
	}	


	while(1){
		sleep(1);
	}

}
//Realize the mutual exclusion mechanism that only one thread is allowed to write files at the same time

14.pipe interprocess communication - anonymous pipe


characteristic:
It can only be used for communication between father and son or brother (kinship)
Simplex means one-way communication
The pipe size is 64K
fd[0] is the read side and fd[1] is the write side
Read unknown pipe
The writer exists: read data when there is data, and block when there is no data
Write side does not exist: return immediately when there is no data
Write unknown pipe
The reading end exists: there is space to write data; No space, blocking
The reading end does not exist: the pipe is broken

Usage example:

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

int main(){
	
	int pfd[2];
	pid_t pid;
	int re;
	//Create pipe before fork
	re = pipe(pfd);
	if(re == -1){
		perror("pipe");
		return -1;
	}
	
	pid = fork();
	if(pid<0){
		perror("fork");
		return -1;
	}else if(pid ==0){
		
		char buf[64] = "haha, I am child,pipe message!\n";
		while(1){
			
			write(pfd[1],buf,strlen(buf));
			sleep(1);
		}
	}else{
		char buf[64];
		while(1){
			memset(buf,0,64);
			re = read(pfd[0],buf,64);
			if(re>0){
				printf("msg from child %s\n",buf);
			}else{
					break;
			}
		}
	}	
}
//The child process sends information to the parent process

15.mkfifo interprocess communication - famous pipeline


characteristic:
It can be used for any interprocess communication;
The reading and writing mode can be specified;
Through file IO operation, the contents are stored in memory
Usage example:
write.c

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
int main(){
	
	int re;
	int fd;
	char buf[32];
	unlink("/myfifo");
	//Initialize the pipe and name it myfifo
	re = mkfifo("/myfifo",0666);
	if(re==-1){
		perror("mkfifo");
		return -1;
	}
	//Open the pipe as a file and specify write only permissions
	fd = open("/myfifo",O_WRONLY);
	if(fd<0){
		perror("open");
		return -1;
	}
	strcpy(buf,"fifo write test");
	
	while(1){
		write(fd,buf,strlen(buf));
		sleep(1);
	}
	
	
	
}

read.c

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
int main(){
	
	int re;
	int fd;
	char buf[32];

	//When reading, open the named pipeline directly and specify the permission to read
	fd = open("/myfifo",O_RDONLY);
	if(fd<0){
		perror("open");
		return -1;
	}
	
	
	while(1){
		memset(buf,0,32);
		read(fd,buf,32);
		printf("%s\n",buf);
		sleep(1);
	}
	
	
	
}

16.kill, raise, alarm, pause interprocess communication - signal correlation function


Common signals:
The signal table can be viewed with the command kill -l

17.signal setting signal capture


Interrupt mechanism: the program executes another program during execution, and then continues to execute the original program after execution
Default mode: when the signal comes, execute the default program
Ignore signal: the signal is coming and will not be executed
Capture signal: when the signal comes, execute the custom program

Usage example:

#include <signal.h>
#include <stdio.h>
void handlefunc(int sig){
	
	if(SIGINT == sig){
		printf("I got SIGINT signal\n");
	}else if(SIGHUP == sig){
		printf("I got SIGHUP signal\n");
	}
	
}


int main(){
	
	signal(SIGINT,handlefunc);
	signal(SIGHUP,handlefunc);
	
	while(1){
		sleep(1);
	}
	
}

18.SIGCHLD subprocess end signal

Because signal processing is asynchronous, the parent process does not have to wait until the child process exits.
Usage example:

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

void asasa(int sig){
	wait(NULL);
}

int main(){
	pid_t pid;
	pid = fork();
	signal(SIGCHLD,asasa);
	if(pid<0){
		perror("fork");
	}else if(pid==0){
		sleep(10);
		exit(0);
		
	}else{
		
	}
	
	while(1){
		printf("hahahah,I am free!!!!!\n");
		sleep(1);
	}
	
}
//The parent process will not be blocked, and the child process will not become a zombie process

19.ftok generate key


Usage example:

20.shmget, shmat, shmdt, shmctl interprocess communication - shared memory

Steps for using shared memory:

Usage example:
shmwrite.c

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

int main(){
	
	key_t key;
	int shmid;
	char *addr;
	
	//Generate key
	key = ftok(".",23);
	if(key==-1){
		perror("ftok");
		return -1;
	}
	//Create shared memory
	shmid = shmget(key,1024,IPC_CREAT|0666);
	if(shmid==-1){
		perror("shmget");
		return -1;
	}
	//Map shared memory
	addr = shmat(shmid,NULL,0);
	
	fget(addr,32,stdin);
	//strcpy(addr,"this my share memeory");
	//Delete shared memory
	shmdt(addr);

	
}

shmread.c

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <string.h>

int main(){
	key_t key;
	int shmid;
	char *addr;	
	
	key = ftok(".",23);
	if(key==-1){
		perror("ftok");
		return -1;
	}
	shmid = shmget(key,1024,IPC_CREAT|0666);
	if(shmid==-1){
		perror("shmget");
		return -1;
	}
	
	addr = shmat(shmid,NULL,0);
	
	//strcpy(addr,"this my share memeory");
	printf("get share mem=%s\n",addr);
	
	
	shmdt(addr);
	//Unload shared memory
	shmctl(shmid,IPC_RMID,NULL);

	
	
}

21. Inter process communication of msgget, msgsnd, msgrcv and msgctl - message queue

Steps for using message queue:

Usage example:
msg_snd.c

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>

typedef struct{
	
	long type;
	char txt[64];
}MSG;
//Size of message content txt
#define LEN sizeof(MSG)-sizeof(long)

int main(){
	
	key_t ipkey;
	int msgid;

	MSG msg_t;
	//Generate key
    ipkey = ftok(".",23);
	if(ipkey==-1){
		perror("ftok");
		return -1;
	}
	//Create message queue
	msgid = msgget(ipkey,IPC_CREAT|0666);
	if(msgid ==-1){
		perror("msgget");
		return -1;
	}
	//Define message type
	msg_t.type = 1;
	strcpy(msg_t.txt,"msg type one");
	//send message
	msgsnd(msgid,&msg_t,LEN,0);

	msg_t.type = 2;
	strcpy(msg_t.txt,"msg type two");
	msgsnd(msgid,&msg_t,LEN,0);
	
	msg_t.type = 3;
	strcpy(msg_t.txt,"msg type three");
	msgsnd(msgid,&msg_t,LEN,0);
	
	msg_t.type = 4;
	strcpy(msg_t.txt,"msg type four");
	msgsnd(msgid,&msg_t,LEN,0);
	
	msg_t.type = 5;
	strcpy(msg_t.txt,"msg type five");
	msgsnd(msgid,&msg_t,LEN,0);

}

msg_rcv.c

#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
//#include <sys/ipc.h>
//#include <sys/msg.h>
#include <linux/msg.h>
#include <string.h>
#include <stdlib.h>

typedef struct{
	
	long type;
	char txt[64];
}MSG;
int msgid;

#define LEN sizeof(MSG)-sizeof(long)
void rmmsg(int sig){
	//Remove message queue
	msgctl(msgid,IPC_RMID,NULL);
	exit(0);
	
}

int main(){
	
	key_t ipkey;
	int re;
	MSG msg_t;
	
    ipkey = ftok(".",23);
	if(ipkey==-1){
		perror("ftok");
		return -1;
	}
	msgid = msgget(ipkey,IPC_CREAT|0666);
	if(msgid ==-1){
		perror("msgget");
		return -1;
	}	
	signal(SIGINT,rmmsg);
	
	while(1){
	//receive messages
		re = msgrcv(msgid,&msg_t,LEN,3,MSG_EXCEPT);//Only messages other than message 3 are received
        //re = msgrcv(msgid,&msg_t,LEN, 0, 0); Receive all messages
        //re = msgrcv(msgid,&msg_t,LEN,3,0); Only type 3 messages are received
		printf("receive msg:type=%d,txt=%s\n",(int)msg_t.type,msg_t.txt);
		if(re<=0){
			break;
		}
	}
	
	

	
	
}

22.semget, semctl, semop interprocess communication - semaphore

Use steps of signal lamp:

Usage example:

//Semaphores are used with shared memory
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <errno.h>
#include <sys/sem.h>
#include <string.h>

union  semun{
	int val;
};

#define SEM_READ 0
#define SEM_WRITE 0
//p-1 operation
poperation(int index,int semid){
	struct  sembuf sop;
	sop.sem_num = index;
	sop.sem_op = -1;
	sop.sem_flg = 0;
	semop(semid,&sop,1);
	
}
//v+1 operation
voperation(int index,int semid){
	struct  sembuf sop;
	sop.sem_num = index;
	sop.sem_op = 1;
	sop.sem_flg = 0;
	semop(semid,&sop,1);	
	
}


int main(){
	
	key_t key;
	int semid;
	int shmid;
	pid_t pid;
	
	char *shmaddr;
	
	key  = ftok(".",123);
	 
	/*Create 2 semaphores*/
	semid = semget(key,2,IPC_CREAT|0777);
	if(semid<0){
		perror("semget");
		return -1;
	}

	
	/*Create shared memory*/
	shmid = shmget(key,256,IPC_CREAT|0777);
	if(shmid<0){
		perror("shmget");
		return -1;
	}	
	
	/* Initialize 2 signal lights*/
	union  semun myun;
	/* Initialize read signal lamp*/
	myun.val = 0;
	semctl(semid,SEM_READ,SETVAL,myun);
	
	/* Initialize write semaphore*/
	myun.val = 1;
	semctl(semid,SEM_WRITE,SETVAL,myun);	

	
	pid = fork();
	if(pid<0){
		perror("fork");
		return -1;
	}else if(pid == 0){
		
		shmaddr = (char*)shmat(shmid,NULL,0);
		while(1){
			poperation(SEM_READ,semid);
			printf("getshm:%s",shmaddr);
			voperation(SEM_WRITE,semid);
		}
		
	}else{
		shmaddr = (char*)shmat(shmid,NULL,0);
		
		while(1){
			poperation(SEM_WRITE,semid);
			printf("please input char to shm:");
			fgets(shmaddr,32,stdin);
			voperation(SEM_READ,semid);
		}
		
	}


}

Network programming

Topics: Embedded system