在 Haskell 中设置 argv[0]? [英] Setting argv[0] in Haskell?

查看:17
本文介绍了在 Haskell 中设置 argv[0]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Haskell 程序中设置 argv[0](比如,一个用 ghc 编译的程序)?

我在 System.Environment 中找到了 getProgNamewithProgName 函数,但它似乎没有改变 ps 报告的内容 (Ubuntu).

import System.Environment主要 =do name <- getProgNameputStrLn $ "你好,我的名字是 " ++ namewithProgName "other" $ do新名称 <- getProgNameputStrLn $ "名称现在设置为 " ++ 新名称putStrLn "你叫什么名字:"-- 允许时间运行 psans <- getLineputStrLn $ "很高兴认识你" ++ ans

解决方案

没有可移植的方式来做到这一点,但在 Linux 2.6.9 及更高版本上,可以使用 prctl() 使用 PR_SET_NAME 操作,所以我们只需要一点点 FFI 即可使用它来自 Haskell.(检查 Hackage 上是否有任何绑定通常是个好主意,但在这种情况下我找不到任何绑定).

{-# LANGUAGE ForeignFunctionInterface #-}进口外国.C国外进口 ccall "sys/prctl.h prctl"prctl :: CInt ->CString ->CULong ->CULong ->CULong ->输入接口setProgName :: 字符串 ->输入口 ()setProgName 标题 =withCString title $ \title' ->做res <- prctl pr_set_name 标题' 0 0 0返回 ()其中 pr_set_name = 15

这似乎适用于更改 ps 所见的名称.但是,getProgName 返回的值在程序启动时似乎已被缓存,因此您必须将其与 withProgName 结合使用才能查看程序中的更改.>

Is there a way to set argv[0] in a Haskell program (say, one compiled with ghc)?

I found the getProgName and withProgName functions in System.Environment, but it doesn't seem to change what ps reports (Ubuntu).

import System.Environment

main =
  do name <- getProgName
     putStrLn $ "Hello, my name is " ++ name
     withProgName "other" $ do
       newname <- getProgName
       putStrLn $ "Name now set to " ++ newname
       putStrLn "What is your name: "
       -- allow time to run ps
       ans <- getLine
       putStrLn $ "Pleased to meet you, " ++ ans

解决方案

There is no portable way of doing this, but on Linux 2.6.9 and up the process name can be changed with prctl() using the PR_SET_NAME operation, so we just need a little bit of FFI to use it from Haskell. (It's usually a good idea to check if there are any bindings on Hackage, but in this case I couldn't find any).

{-# LANGUAGE ForeignFunctionInterface #-}

import Foreign.C

foreign import ccall "sys/prctl.h prctl"
  prctl :: CInt -> CString -> CULong -> CULong -> CULong -> IO CInt

setProgName :: String -> IO ()
setProgName title =
  withCString title $ \title' -> do
    res <- prctl pr_set_name title' 0 0 0
    return ()
  where pr_set_name = 15

This seems to work fine for changing the name as seen by ps. However, the value returned by getProgName appears to be cached when the program starts, so you'll have to combine this with withProgName to see the change within your program.

这篇关于在 Haskell 中设置 argv[0]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆