Question

Context

I am a self learning and I got my first socket working today with c code. Glad.

Problem

Say we have sfd, a socket file descriptor.

When executing this code :

flags = fcntl (sfd, F_GETFL, 0);
printf("FD MODE 1 - %d\n",fcntl(sfd,F_GETFL));
flags |= O_NONBLOCK;
s = fcntl (sfd, F_SETFL, flags);
printf("FD MODE 2 - %d\n",fcntl(sfd,F_GETFL));

it outputs:

2
2050

But my fcntl-linux.h says :

...
/* open/fcntl.  */
#define O_ACCMODE      0003
#define O_RDONLY         00
#define O_WRONLY         01
#define O_RDWR           02
#ifndef O_CREAT
# define O_CREAT       0100 /* Not fcntl.  */
#endif
#ifndef O_EXCL
# define O_EXCL        0200 /* Not fcntl.  */
#endif
#ifndef O_NOCTTY
# define O_NOCTTY      0400 /* Not fcntl.  */
#endif
#ifndef O_TRUNC
# define O_TRUNC      01000 /* Not fcntl.  */
#endif
#ifndef O_APPEND
# define O_APPEND     02000
#endif
#ifndef O_NONBLOCK
# define O_NONBLOCK   04000
....

Question

Even with bitwise operations I cannot afford to get how I finally get 2050 or 2.

Anyone to clear the path for me?

Was it helpful?

Solution

04000 (with the leading zero) is an octal integer literal, and

   2 (decimal) =    2 (octal) = O_RDWR
2050 (decimal) = 4002 (octal) = O_RDWR | O_NONBLOCK

which means that setting the O_NONBLOCK flag just worked fine.

For easier comparison with the O_XXX definitions you could print the flags as an octal number:

printf("FD MODE 2 - %#o\n", fcntl(sfd,F_GETFL));
// Output: FD MODE 2 - 04002
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top