Header file:
stdio.h
Synopsis:
char * strerror_r (int errnum, char *buf, size t n)
Description:
It is similar to strerror and it returns a string describing the error number.
It is thread safe and mostly used in multi-threaded programs.
Sample Program for strerror_r in C:
#include<stdio.h>
#include<string.h>
#include<errno.h>
int main(int argc, char **argv) {
FILE *fp;
char buffer[50];
int err;
fp = fopen(argv[1], "r");
if (fp == NULL) {
/* errno - available in errno.h */
err = strerror_r(errno, buffer, 50);
printf("Error message=> %s\n", buffer);
printf("Return value: %d\n", err);
return;
}
fclose(fp);
return 0;
}
Output:
jp@jp-VirtualBox:~/cpgms/chap2$ ls
a.out strerror.c strerror_r.c strerror_r_ts.c
jp@jp-VirtualBox:~/cpgms/chap2$ ./a.out jp.txt
Error message=> No such file or directory
Return value: 0
jp@jp-VirtualBox:~/cpgms/chap2$
Sample program for strerror_r in threads:
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<pthread.h>
pthread_t thread_id;
void *
thr_fn(void *errnum)
{
char buffer[256];
int err;
err = strerror_r(*((int *)errnum), buffer, 256);
printf("Error: %s\n", buffer);
printf("Return value:%d\n", err);
return ((void *)0);
}
int
main(int argc, char **argv)
{
FILE *fp;
int err;
fp = fopen(argv[1], "r");
if (fp == NULL) {
err = pthread_create(&thread_id, NULL, thr_fn, &errno);
if (err != 0)
printf("can't create thread: %s\n", strerror(err));
}
sleep(1);
return 0;
}
#include<string.h>
#include<errno.h>
#include<pthread.h>
pthread_t thread_id;
void *
thr_fn(void *errnum)
{
char buffer[256];
int err;
err = strerror_r(*((int *)errnum), buffer, 256);
printf("Error: %s\n", buffer);
printf("Return value:%d\n", err);
return ((void *)0);
}
int
main(int argc, char **argv)
{
FILE *fp;
int err;
fp = fopen(argv[1], "r");
if (fp == NULL) {
err = pthread_create(&thread_id, NULL, thr_fn, &errno);
if (err != 0)
printf("can't create thread: %s\n", strerror(err));
}
sleep(1);
return 0;
}
Output:
jp@jp-VirtualBox:~/cpgms/chap2$ gcc strerror_r_ts.c -lpthread
jp@jp-VirtualBox:~/cpgms/chap2$ ls
a.out strerror.c strerror_r.c strerror_r_ts.c
jp@jp-VirtualBox:~/cpgms/chap2$ ./a.out jp.txt
Error: No such file or directory
Return value:0
jp@jp-VirtualBox:~/cpgms/chap2$
jp@jp-VirtualBox:~/cpgms/chap2$ ls
a.out strerror.c strerror_r.c strerror_r_ts.c
jp@jp-VirtualBox:~/cpgms/chap2$ ./a.out jp.txt
Error: No such file or directory
Return value:0
jp@jp-VirtualBox:~/cpgms/chap2$
No comments:
Post a Comment