小编pec*_*nie的帖子

"fork()"之后的printf异常

操作系统:Linux,语言:纯C

我正在学习一般的C编程,以及在特殊情况下在UNIX下进行C编程.

printf()在使用fork()呼叫后,我发现了一个奇怪的(对我来说)函数的行为.

#include <stdio.h>
#include <system.h>

int main()
{
    int pid;
    printf( "Hello, my pid is %d", getpid() );

    pid = fork();
    if( pid == 0 )
    {
            printf( "\nI was forked! :D" );
            sleep( 3 );
    }
    else
    {
            waitpid( pid, NULL, 0 );
            printf( "\n%d was forked!", pid );
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

产量

Hello, my pid is 1111
I was forked! :DHello, my pid is 1111
2222 was forked!
Run Code Online (Sandbox Code Playgroud)

为什么第二个"Hello"字符串出现在子输出中?

是的,这正是父母在开始时与父母一起打印的内容pid …

c unix linux printf fork

66
推荐指数
3
解决办法
3万
查看次数

在C中的单独函数中初始化指针

我需要做一个简单的事情,我过去常常用Java做过很多次,但我陷入了C(纯C,而不是C++).情况如下:

int *a;

void initArray( int *arr )
{
    arr = malloc( sizeof( int )  * SIZE );
}

int main()
{
    initArray( a );
    // a is NULL here! what to do?!
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我有一些"初始化"函数,它应该给一些指定的指针分配一些分配的数据(无关紧要).我应该如何给一个函数指针,以便对这个指针进行修改,然后可以在代码中进一步使用(在该函数调用之后返回)?

c pointers initializing

15
推荐指数
2
解决办法
7881
查看次数

haskell中子串替换的最佳方法

问题很简单:我必须用"xyz"替换所有出现的"fooo"及其所有子串.例如,在Java中,我将这样做:

someString.replaceAll( "fooo|foo|fo", "xyz" )
Run Code Online (Sandbox Code Playgroud)

它会做的伎俩.但在Haskell中,我发现没有有效的方法来使用正则表达式.首先,我读过这个:http://www.haskell.org/haskellwiki/Regular_expressions

实际上具有replace函数的唯一库是regex-posix,但它在性能上被认为"非常慢".这个事实是不可接受的.另外我发现这个replace函数由于任何原因不符合给定模式的顺序,所以我得到这样的输出:

>replace "boo fooo boo" "xyz"
"boo xyzoo boo"
Run Code Online (Sandbox Code Playgroud)

其他后端并不意味着这样的功能.

所以我决定写简单的解决方法:

replaceFoo input =
    helper input []
    where
        helper ('f':'o':'o':'o':xs) ys = helper xs ("zyx" ++ ys)
        helper ('f':'o':'o':xs) ys = helper xs ("zyx" ++ ys)
        helper ('f':'o':xs) ys = helper xs ("zyx" ++ ys)
        helper (x:xs) ys = helper xs (x:ys)
        helper [] ys = reverse ys
Run Code Online (Sandbox Code Playgroud)

虽然我发现这个功能不太好,但效果很好而且速度很快.但是现在我遇到了在这个替换中添加更多单词的必要性,我不喜欢扩展helper模式的想法(我需要说实际应用程序中我实际上有4个单词,这很奇怪).

如果有人帮助我快速解决方案,我会很高兴.


cebewee,感谢Data.String.Utils.但我担心如果要替换很多单词("fooo"到"xyz","foo"到"xyz","fo"到"xyz","bar"到"quux"等等,这种方法很慢),因为为了foldr …

haskell replace substring

7
推荐指数
2
解决办法
5163
查看次数

标签 统计

c ×2

fork ×1

haskell ×1

initializing ×1

linux ×1

pointers ×1

printf ×1

replace ×1

substring ×1

unix ×1