Is using fcntl F_SETLKW on STDOUT_FILENO legal?fcntl, lockf, which is better to use for file locking?fcntl substitute on Windowsfcntl() for thread or process synchronization?What does the FD_CLOEXEC fcntl() flag do?fcntl() scope visibility behavior?The difference between stdout and STDOUT_FILENO in LINUX Cfcntl with F_SETLKWhat is the difference between locking with `fcntl` and `flock`?Blocking recv() vs fcntl()what is the usage of F_DUPFD inside fcntl in Linux system call

Re-testing of regression test bug fixes or re-run regression tests?

How do I adjust encounters to challenge my lycanthrope players without negating their cool new abilities?

Can I say: "When was your train leaving?" if the train leaves in the future?

How to cope with regret and shame about not fully utilizing opportunities during PhD?

How to disable Two-factor authentication for Apple ID?

Formal Definition of Dot Product

complicated arrows in flowcharts

What information exactly does an instruction cache store?

Meaning of "work with shame"

Did galley captains put corks in the mouths of slave rowers to keep them quiet?

Developers demotivated due to working on same project for more than 2 years

Substring join or additional table, which is faster?

A case where Bishop for knight isn't a good trade

Spark Double copying my planeswalker - do I have to sacrifice?

Why doesn't Iron Man's action affect this person in Endgame?

Will casting a card from the graveyard with Flashback add a quest counter on Pyromancer Ascension?

Alexa-rank complaining about insecure generator meta-tag

Why does SSL Labs now consider CBC suites weak?

How might a landlocked lake become a complete ecosystem?

Source of the Wildfire?

Why do the lights go out when someone enters the dining room on this ship?

is it correct to say "When it started to rain, I was in the open air."

Wireless headphones interfere with Wi-Fi signal on laptop

Why does lemon juice reduce the "fish" odor of sea food — specifically fish?



Is using fcntl F_SETLKW on STDOUT_FILENO legal?


fcntl, lockf, which is better to use for file locking?fcntl substitute on Windowsfcntl() for thread or process synchronization?What does the FD_CLOEXEC fcntl() flag do?fcntl() scope visibility behavior?The difference between stdout and STDOUT_FILENO in LINUX Cfcntl with F_SETLKWhat is the difference between locking with `fcntl` and `flock`?Blocking recv() vs fcntl()what is the usage of F_DUPFD inside fcntl in Linux system call






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I have multiple processes spawned via fork from main program, which means they output to same stdout (which I want). However I need to somehow prevent the output from being interleaved. I already use fcntl locks to synchronize access to log file so I wanted to use it also for stdout.



However this blog post claims that fcntl locks are associated with an [i-node, pid] pair. Do stdout have an inode? I've decided to just try it



#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>

void do_log(const char *msg)
printf("%5ld: %sn", getpid(), msg);


void try_lock(void)
do_log("Trying to lock stdout...");

struct flock fl =
.l_type = F_WRLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0,
;
if (fcntl(STDOUT_FILENO, F_SETLKW, &fl) == -1)
perror("fcntl - lock");
exit(1);


do_log("Stdout locked");
sleep(2);
do_log("Trying to unlock stdout...");

fl.l_type = F_UNLCK;
if (fcntl(STDOUT_FILENO, F_SETLKW, &fl) == -1)
perror("fcntl - unlock");
exit(1);


do_log("Stdout unlocked");


int main(void)
if (fork())
try_lock();
else
try_lock();

wait(NULL);
return 0;



which seems to work



17156: Trying to lock stdout...
17155: Trying to lock stdout...
17155: Stdout locked
17155: Trying to unlock stdout...
17155: Stdout unlocked
17156: Stdout locked
17156: Trying to unlock stdout...
17156: Stdout unlocked


but in manpage for fcntl I've noticed If fildes refers to a typed memory object, the result of the fcntl() function is unspecified. and I have no idea what that means.



So I guess I have two questions:



  1. Is using fcntl lock on stdout like this guaranteed to work?

  2. If answer to 1. is yes, is the blog post wrong about [i-node, pid] or does stdout actually have an i-node?









share|improve this question
























  • It is unlikely that standard input would be a 'typed memory object'. That requires special work to set it up.

    – Jonathan Leffler
    Mar 24 at 1:52

















2















I have multiple processes spawned via fork from main program, which means they output to same stdout (which I want). However I need to somehow prevent the output from being interleaved. I already use fcntl locks to synchronize access to log file so I wanted to use it also for stdout.



However this blog post claims that fcntl locks are associated with an [i-node, pid] pair. Do stdout have an inode? I've decided to just try it



#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>

void do_log(const char *msg)
printf("%5ld: %sn", getpid(), msg);


void try_lock(void)
do_log("Trying to lock stdout...");

struct flock fl =
.l_type = F_WRLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0,
;
if (fcntl(STDOUT_FILENO, F_SETLKW, &fl) == -1)
perror("fcntl - lock");
exit(1);


do_log("Stdout locked");
sleep(2);
do_log("Trying to unlock stdout...");

fl.l_type = F_UNLCK;
if (fcntl(STDOUT_FILENO, F_SETLKW, &fl) == -1)
perror("fcntl - unlock");
exit(1);


do_log("Stdout unlocked");


int main(void)
if (fork())
try_lock();
else
try_lock();

wait(NULL);
return 0;



which seems to work



17156: Trying to lock stdout...
17155: Trying to lock stdout...
17155: Stdout locked
17155: Trying to unlock stdout...
17155: Stdout unlocked
17156: Stdout locked
17156: Trying to unlock stdout...
17156: Stdout unlocked


but in manpage for fcntl I've noticed If fildes refers to a typed memory object, the result of the fcntl() function is unspecified. and I have no idea what that means.



So I guess I have two questions:



  1. Is using fcntl lock on stdout like this guaranteed to work?

  2. If answer to 1. is yes, is the blog post wrong about [i-node, pid] or does stdout actually have an i-node?









share|improve this question
























  • It is unlikely that standard input would be a 'typed memory object'. That requires special work to set it up.

    – Jonathan Leffler
    Mar 24 at 1:52













2












2








2








I have multiple processes spawned via fork from main program, which means they output to same stdout (which I want). However I need to somehow prevent the output from being interleaved. I already use fcntl locks to synchronize access to log file so I wanted to use it also for stdout.



However this blog post claims that fcntl locks are associated with an [i-node, pid] pair. Do stdout have an inode? I've decided to just try it



#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>

void do_log(const char *msg)
printf("%5ld: %sn", getpid(), msg);


void try_lock(void)
do_log("Trying to lock stdout...");

struct flock fl =
.l_type = F_WRLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0,
;
if (fcntl(STDOUT_FILENO, F_SETLKW, &fl) == -1)
perror("fcntl - lock");
exit(1);


do_log("Stdout locked");
sleep(2);
do_log("Trying to unlock stdout...");

fl.l_type = F_UNLCK;
if (fcntl(STDOUT_FILENO, F_SETLKW, &fl) == -1)
perror("fcntl - unlock");
exit(1);


do_log("Stdout unlocked");


int main(void)
if (fork())
try_lock();
else
try_lock();

wait(NULL);
return 0;



which seems to work



17156: Trying to lock stdout...
17155: Trying to lock stdout...
17155: Stdout locked
17155: Trying to unlock stdout...
17155: Stdout unlocked
17156: Stdout locked
17156: Trying to unlock stdout...
17156: Stdout unlocked


but in manpage for fcntl I've noticed If fildes refers to a typed memory object, the result of the fcntl() function is unspecified. and I have no idea what that means.



So I guess I have two questions:



  1. Is using fcntl lock on stdout like this guaranteed to work?

  2. If answer to 1. is yes, is the blog post wrong about [i-node, pid] or does stdout actually have an i-node?









share|improve this question
















I have multiple processes spawned via fork from main program, which means they output to same stdout (which I want). However I need to somehow prevent the output from being interleaved. I already use fcntl locks to synchronize access to log file so I wanted to use it also for stdout.



However this blog post claims that fcntl locks are associated with an [i-node, pid] pair. Do stdout have an inode? I've decided to just try it



#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>

void do_log(const char *msg)
printf("%5ld: %sn", getpid(), msg);


void try_lock(void)
do_log("Trying to lock stdout...");

struct flock fl =
.l_type = F_WRLCK,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0,
;
if (fcntl(STDOUT_FILENO, F_SETLKW, &fl) == -1)
perror("fcntl - lock");
exit(1);


do_log("Stdout locked");
sleep(2);
do_log("Trying to unlock stdout...");

fl.l_type = F_UNLCK;
if (fcntl(STDOUT_FILENO, F_SETLKW, &fl) == -1)
perror("fcntl - unlock");
exit(1);


do_log("Stdout unlocked");


int main(void)
if (fork())
try_lock();
else
try_lock();

wait(NULL);
return 0;



which seems to work



17156: Trying to lock stdout...
17155: Trying to lock stdout...
17155: Stdout locked
17155: Trying to unlock stdout...
17155: Stdout unlocked
17156: Stdout locked
17156: Trying to unlock stdout...
17156: Stdout unlocked


but in manpage for fcntl I've noticed If fildes refers to a typed memory object, the result of the fcntl() function is unspecified. and I have no idea what that means.



So I guess I have two questions:



  1. Is using fcntl lock on stdout like this guaranteed to work?

  2. If answer to 1. is yes, is the blog post wrong about [i-node, pid] or does stdout actually have an i-node?






c linux synchronization posix






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 13:48







graywolf

















asked Mar 23 at 13:43









graywolfgraywolf

2,65152954




2,65152954












  • It is unlikely that standard input would be a 'typed memory object'. That requires special work to set it up.

    – Jonathan Leffler
    Mar 24 at 1:52

















  • It is unlikely that standard input would be a 'typed memory object'. That requires special work to set it up.

    – Jonathan Leffler
    Mar 24 at 1:52
















It is unlikely that standard input would be a 'typed memory object'. That requires special work to set it up.

– Jonathan Leffler
Mar 24 at 1:52





It is unlikely that standard input would be a 'typed memory object'. That requires special work to set it up.

– Jonathan Leffler
Mar 24 at 1:52












1 Answer
1






active

oldest

votes


















1














An inode number (along with device number) is purely a unique identifier for a file. It has nothing to do, in modern usage of the term, with on-disk filesystem structures. All files (and file descriptors refer to instances of open files) have an inode number, and doing fcntl at least "makes sense" on them. However, per POSIX:




Record locking shall be supported for regular files, and may be supported for other files.




It's possible that there are some file types on which Linux doesn not support locks; I'm not sure.



Note also that locking is purely advisory - it has no effect if the processes doing the writing don't attempt to take the lock before performing their access.



It may make more sense, especially if you're using fork without exec, to do locking via shared memory. Before forking, mmap a MAP_ANON|MAP_SHARED region and setup a process-shared mutex in it. You can make this a robust mutex if any process might be able to die unexpectedly. This is guaranteed to work, and should be faster too since it's purely a userspace operation except on lock contention.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55314329%2fis-using-fcntl-f-setlkw-on-stdout-fileno-legal%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    An inode number (along with device number) is purely a unique identifier for a file. It has nothing to do, in modern usage of the term, with on-disk filesystem structures. All files (and file descriptors refer to instances of open files) have an inode number, and doing fcntl at least "makes sense" on them. However, per POSIX:




    Record locking shall be supported for regular files, and may be supported for other files.




    It's possible that there are some file types on which Linux doesn not support locks; I'm not sure.



    Note also that locking is purely advisory - it has no effect if the processes doing the writing don't attempt to take the lock before performing their access.



    It may make more sense, especially if you're using fork without exec, to do locking via shared memory. Before forking, mmap a MAP_ANON|MAP_SHARED region and setup a process-shared mutex in it. You can make this a robust mutex if any process might be able to die unexpectedly. This is guaranteed to work, and should be faster too since it's purely a userspace operation except on lock contention.






    share|improve this answer



























      1














      An inode number (along with device number) is purely a unique identifier for a file. It has nothing to do, in modern usage of the term, with on-disk filesystem structures. All files (and file descriptors refer to instances of open files) have an inode number, and doing fcntl at least "makes sense" on them. However, per POSIX:




      Record locking shall be supported for regular files, and may be supported for other files.




      It's possible that there are some file types on which Linux doesn not support locks; I'm not sure.



      Note also that locking is purely advisory - it has no effect if the processes doing the writing don't attempt to take the lock before performing their access.



      It may make more sense, especially if you're using fork without exec, to do locking via shared memory. Before forking, mmap a MAP_ANON|MAP_SHARED region and setup a process-shared mutex in it. You can make this a robust mutex if any process might be able to die unexpectedly. This is guaranteed to work, and should be faster too since it's purely a userspace operation except on lock contention.






      share|improve this answer

























        1












        1








        1







        An inode number (along with device number) is purely a unique identifier for a file. It has nothing to do, in modern usage of the term, with on-disk filesystem structures. All files (and file descriptors refer to instances of open files) have an inode number, and doing fcntl at least "makes sense" on them. However, per POSIX:




        Record locking shall be supported for regular files, and may be supported for other files.




        It's possible that there are some file types on which Linux doesn not support locks; I'm not sure.



        Note also that locking is purely advisory - it has no effect if the processes doing the writing don't attempt to take the lock before performing their access.



        It may make more sense, especially if you're using fork without exec, to do locking via shared memory. Before forking, mmap a MAP_ANON|MAP_SHARED region and setup a process-shared mutex in it. You can make this a robust mutex if any process might be able to die unexpectedly. This is guaranteed to work, and should be faster too since it's purely a userspace operation except on lock contention.






        share|improve this answer













        An inode number (along with device number) is purely a unique identifier for a file. It has nothing to do, in modern usage of the term, with on-disk filesystem structures. All files (and file descriptors refer to instances of open files) have an inode number, and doing fcntl at least "makes sense" on them. However, per POSIX:




        Record locking shall be supported for regular files, and may be supported for other files.




        It's possible that there are some file types on which Linux doesn not support locks; I'm not sure.



        Note also that locking is purely advisory - it has no effect if the processes doing the writing don't attempt to take the lock before performing their access.



        It may make more sense, especially if you're using fork without exec, to do locking via shared memory. Before forking, mmap a MAP_ANON|MAP_SHARED region and setup a process-shared mutex in it. You can make this a robust mutex if any process might be able to die unexpectedly. This is guaranteed to work, and should be faster too since it's purely a userspace operation except on lock contention.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 23 at 13:58









        R..R..

        159k27266571




        159k27266571





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55314329%2fis-using-fcntl-f-setlkw-on-stdout-fileno-legal%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

            155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해